$(document).ready(function(){

    initializeSliderBtn();
    
    // Attach events to page buttons
    $('.page-1-btn').live('click',function(){
        if(!$(this).hasClass('box-disabled')) {
            slideto(1);
        }
    });
    
    $('.page-2-btn').live('click',function(){
        if(!$(this).hasClass('box-disabled')) {
            slideto(2);
        }
    });
    
    $('.page-3-btn').live('click',function(){
        if(!$(this).hasClass('box-disabled')) {
            slideto(3);
        }
    });
    
    $('.help').live('click',function(){
        slideto(4);
    });
    
    $('.sendtofriend').live('click',function(){
        slideto(5);
    });
    


    // Show check box on option checkboxes
    $('.option-container').live('mouseenter',function(){
        if(!$(this).find('.option-checkbox').find('.checkbox').attr('checked')) {
            $(this).find('.option-checkbox').append('<div class="option-checked-green"></div>');
        }
    }).live('mouseleave',function(){
        if(!$(this).find('.option-checkbox').find('.checkbox').attr('checked')) {
            $(this).find('.option-checked-green').remove();
        }
    }).live('click',function(){
        if($(this).find('.option-checkbox').find('.checkbox').attr('checked')) {
            // uncheck the checkbox
            $(this).find('.option-checkbox').find('.checkbox').removeAttr('checked',false);
            handleCheckboxes();
            $(this).removeClass('option-selected');
        } else {
            // check the checkbox
            $(this).find('.option-checkbox').find('.checkbox').attr('checked',true);
            handleCheckboxes();
            // mark the box as selected
            $(this).addClass('option-selected');
        }
    });    
    
    // Initialize the checkboxes when checked by default on page load
    handleCheckboxes();
    
    
    // initialize jquery form ajax
    $('form#etSubscriberDetails').submit(function() { 
        $.post('http://cl.exct.net/subscribe.aspx?lid=3996639', {
        	'lead_origin':'profile',
        	'MID':65863,
        	'thx':'http://profile.nnit.com',
        	'err':'http://profile.nnit.com',
        	'Subscriber Key':'',
        	'Email Address':$('input[name="attribute_5"]').val()
        });
        
        var formOptions = {
            success : submitSuccessCallback,
            url : 'lib/etSubmitUser.php',
            beforeSubmit: validate,
            type: 'post',
            dataType : 'json'
        };
       
        $(this).ajaxSubmit(formOptions); 
         // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    }); 
    
    // attach submit triger for form#etSubscriberDetails
    $('.etSubscriberDetailsSubmit').live('click',function(){
        $('form#etSubscriberDetails').submit();
    });
    
    // initialize jquery form ajax
    $('form#sendtofriend').submit(function() { 
        var formOptions = {
            success : stfSuccessCallback,
            url : 'lib/sendtofriend.php',
            beforeSubmit: stfValidate,
            type: 'post',
            clearForm: true,
            resetForm: true
        };
       
        $(this).ajaxSubmit(formOptions); 
         // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    }); 
    
    // initialize jquery form ajax
    $('form#contact-us').submit(function() { 
        var formOptions = {
            success : cuSuccessCallback,
            url : 'lib/contact-us.php',
            beforeSubmit: cuValidate,
            type: 'post'
        };
       
        $(this).ajaxSubmit(formOptions); 
         // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    }); 
    
 
    $('form#getUserForm').submit(function(){
        var formOptions = {
            success : upSuccessCallback,
            url : 'lib/sendUpdateProfileLink.php',
            beforeSubmit: upValidate,
            type: 'post',
            dataType:'json'
        };
       
        $(this).ajaxSubmit(formOptions);  
            
        //$.post('lib/sendUpdateProfileLink.php', { email : $(this).find('input[name="email"]').val() }, function(){
            //alert( $('div.misc .alert6').html() );
          
        //    $('.signin-popup').hide(); 
        //    $('.emailsent-popup').toggle();
          
                    
           // setTimeout( function(){$("#dialog").dialog("destroy");},3000);
           
            /*$( "#dialog:ui-dialog" ).dialog('destroy');
            $( "#dialog-message" ).dialog({
               modal: true,
               width:"280",
               height:"180",
               resizable: false,
               draggable: false,
               buttons: {
                    Ok: function() {
                        $( this ).dialog( "close" );
                    }
                },
                
               
            });
            
             setTimeout(function(){$( "#dialog-message" ).dialog('close');},3000);        
            
            $(this).find('input[name="email"]').val('');
            $('.signin-popup').hide();*/
        //});
       // setTimeout($( "#dialog:ui-dialog" ).dialog('destroy'),3000); // 5 seconds
       
        
        
        return false;
    });
    function upValidate(formData, jqForm, options)
    {
        for (var i=0; i < formData.length; i++) { 
            switch(formData[i].name) {
                case 'email' : 
                    if(!isValidEmail(formData[i].value)) {
                        $("#inputtxt").css({
                        border: "1px solid red"                        
                        });
                        $("#emailtxt").focus();
                        return false;   
                    }
                break;
            }
        }
    }   
    
    function upSuccessCallback(responseText, statusText, xhr, $form)
    {
        if(responseText.userExist == true)
        {
            $("#inputtxt").css({border: "none"});
            $("#update_profile_box").css("display","");
            $("#err_msg").css("display","none");
            $('.signin-popup').hide(); 
            $('.emailsent-popup').toggle(); 
        }else
        {
            $("#inputtxt").css({border: "1px solid red"});
            $("#emailtxt").focus();
            $("#update_profile_box").css("display","none");
            $("#err_msg").css("display","");
        }
    }

    //for closing
    document.onclick=check;
    function check(e)
    {
        var target = (e && e.target) || (event && event.srcElement);
        var obj = document.getElementById('mydiv');
        var obj2 = document.getElementById('obj2');
        
     
        
        checkParent(target)?obj.style.display='none':null;
        target==obj2?obj.style.display='block':null;
       
       
    
    }

    function checkParent(t)
    {
        while(t.parentNode)
        {
            if(t==document.getElementById('mydiv'))
            {
                return false
            }

            t=t.parentNode
        }
        return true
    }
    
    
    $('#getemailsent').mouseleave(function(){
        $('.emailsent-popup').hide();
    })
    //$('#getUserForm').mouseleave(function(){
       // $('.signin-popup').hide();
    //})
    
   
    // sign in trigger
    $('.trigger-signin').click(function(){
        $('.signin-popup').toggle();
        $('#emailtxt').focus();
        
    });
    
    
    
    
    $('.selectbox').bind('change',function(){ 
        handleSelectBoxes();
    });
    
    handleSelectBoxes();
    
    handleHelpOptions();
    
    // toggle contact form
    $('.contactform-trigger').bind('click',function(){
        var thisInfoBox = $(this).attr('connectwith');
        $('.' + thisInfoBox).toggle();
    });
	
});


function getUserDetails(email)
{

    addPreloader();
    
    $.getJSON('lib/etGetUser.php?email=' + email, function(data){
        $('div.main-content').find('.preloader').remove();
        slideto(1);
        // check boxes
        if(data.bulletin == 'true' || data.bulletin == 'TRUE') {
            $('input[name="attribute_2"]').attr('checked',true);
        }
        if(data.life_sciences == 'true' || data.life_sciences == 'TRUE') {
            $('input[name="attribute_3"]').attr('checked',true);
        }
        if(data.job_news == 'true' || data.job_news == 'TRUE'){
            $('input[name="attribute_4"]').attr('checked',true);
        }
        if(data.advisory_services == 'true' || data.advisory_services == 'TRUE') {
            $('input[name="attribute_30"]').attr('checked',true);
        }
        if(data.business_solutions == 'true' || data.business_solutions == 'TRUE') {
            $('input[name="attribute_31"]').attr('checked',true);
        }
        if(data.ls == 'true' || data.ls == 'TRUE') {
           $('input[name="attribute_32"]').attr('checked',true);
        }
        if(data.infrastructure == 'true' || data.infrastructure == 'TRUE') {
            $('input[name="attribute_33"]').attr('checked',true);
        }
        if(data.application == 'true' || data.application == 'TRUE') {
            $('input[name="attribute_34"]').attr('checked',true);        
        }
        if(data.support == 'true' || data.support == 'TRUE') {
            $('input[name="attribute_35"]').attr('checked',true);
        }
        handleCheckboxes();
        
        // textboxes
        $('input[name="attribute_5"]').val(data.email_address);
        $('input[name="attribute_6"]').val(data.full_name);
        $('input[name="attribute_8"]').val(data.company);
        $('input[name="attribute_7"]').val(data.job_title);
        $('input[name="attribute_9"]').val(data.address);
        $('input[name="attribute_10"]').val(data.zip);
        $('input[name="attribute_11"]').val(data.city);
        $('input[name="attribute_12"]').val(data.country);
        $('input[name="attribute_13"]').val(data.phone);
        $('input[name="attribute_14"]').val(data.mobile);
        
        
        
        
        var type_of_industry_dp_2_val = '';  
        // select boxes
        //handle_type_of_industry_dp_1();
        if(data.industry_life_sciences != '' && data.industry_life_sciences!= '- - - -') {
            $('select[name="type_of_industry_dp_1"]').val('Industry_Life_Sciences');
            //$('select[name="type_of_industry_dp_2"]').val(data.industry_life_sciences);
            type_of_industry_dp_2_val = data.industry_life_sciences;
        }
        if(data.public_sector != '' && data.public_sector!= '- - - -') {
            $('select[name="type_of_industry_dp_1"]').val('Public Sector');
            //$('select[name="type_of_industry_dp_2"]').val(data.public_sector);
            type_of_industry_dp_2_val = data.public_sector;
        }
        
        if(data.private_sector != '' && data.private_sector!= '- - - -') {
            $('select[name="type_of_industry_dp_1"]').val('Private Sector');
           // $('select[name="type_of_industry_dp_2"]').val(data.private_sector);
            type_of_industry_dp_2_val = data.private_sector;
        }
  
  // update the industry select options
  var val = $('select[name="type_of_industry_dp_1"]').val();          
  $.post('lib/manage-selectbox.php?token='+Math.random() , {'type_of_industry_dp_1' : val}, function(data){
   if(data != '') {
    $('select[name="type_of_industry_dp_2"]').html(data);
    $('select[name="type_of_industry_dp_2"]').val(type_of_industry_dp_2_val);
    handleSelectBoxes();
   }
  });
  
  // update profile
  var profile = data.profile;
  var val = $('select[name="type_of_industry_dp_1"]').val();
  $.post('lib/manage-profile-selectbox.php?token='+Math.random(), {'type_of_industry_dp_1' : val}, function(data){
   if(data != '') {
    $('select[name="attribute_16"]').html(data); //alert(data);
    $('select[name="attribute_16"]').val(profile);
    handleSelectBoxes();
   }
  });
  
        //handleSelectBoxes();
    });

}

// contact us callback
function cuSuccessCallback(responseText, statusText, xhr, $form)
{
    $('div.main-content').find('.preloader').remove();    

    if(responseText == 'success') {
        $('form#contact-us').hide();
        $('#contact-us-signoff').show();
        setTimeout('cuClearSignoff()',3000);    
    } else {
        alert('An error has occurred while processing your request. Please try again.');
              
    }
}

function cuClearSignoff()
{
    $('.contact').hide();
    $('form#contact-us').show();
    $('#contact-us-signoff').hide();
}

function cuValidate(formData, jqForm, options)  
{
    for (var i=0; i < formData.length; i++) { 
        switch(formData[i].name) 
        {
            case 'name' : 
                if(formData[i].value=='') {
                    alert( $('div.misc .alert2').html() );
                    return false;
                }
            break;
            case 'email' : 
                if(!isValidEmail(formData[i].value)) {
                    alert( $('div.misc .alert1').html() );
                    return false;
                }
            break;
            

        }
    } 
    addPreloader();
    return true;  
}


// send to friend submit callback
function stfSuccessCallback(responseText, statusText, xhr, $form)
{
    $('div.main-content').find('.preloader').remove();    
    if(responseText == 'success') {
        //alert( $('div.misc .alert6').html() );
        
    /*
	$( "#dialog:ui-dialog" ).dialog('destroy');
        $( "#dialog-message" ).dialog(
        {
           modal: true,
           width:"280",
           height:"180",
           resizable: false,
           draggable: false,
           buttons: {
                Ok: function() {
                    $( this ).dialog( "close" );
                }
            }
            
           
        });
        
    setTimeout(function(){$( "#dialog-message" ).dialog('close');},3000);        
	*/
	
	    // set the pop up container
	
	var popupMessageBox = $('.pop-up-message-container');
	
	popupMessageBox.parent().show();
	
	var height = popupMessageBox .height();
	var parentHeight = popupMessageBox .parent().height();
	var marginTop = (parentHeight/2) - height;
	popupMessageBox.css({ marginTop: marginTop });
	
	setTimeout(function(){ popupMessageBox.parent().hide() },3000); 
        
    $(this).find('input[name="email"]').val('');
    $('.signin-popup').hide();
        
    } else {
        alert('An error has occurred while processing your request.');
    }
}
function stfValidate(formData, jqForm, options)  
{ 
    for (var i=0; i < formData.length; i++) { 
        switch(formData[i].name) {
            case 'stfRecEmail' : 
                if(!isValidEmail(formData[i].value)) {
                    alert( $('div.misc .alert7').html() );
                    return false;
                }
            break;
            case 'stfEmail' : 
                if(!isValidEmail(formData[i].value)) {
                    alert( $('div.misc .alert8').html() );
                    return false;
                }
            break;
        }
    } 
    addPreloader();
    return true;  
}


// before submit callback
// validate inputs
function validate(formData, jqForm, options) 
{  
    
    for (var i=0; i < formData.length; i++) { 
        switch(formData[i].name) {
            case 'attribute_5' : 
                if(!isValidEmail(formData[i].value)) {
                    alert( $('div.misc .alert1').html() );
                    return false;
                }
            break;
            case 'attribute_6' : 
                if(!isValidFullname(formData[i].value)) {
                    alert( $('div.misc .alert2').html() );
                    return false;
                }
            break;
            case 'attribute_8' : 
                if(formData[i].value == '') {
                    alert( $('div.misc .alert3').html() );
                    return false;
                }
            break;
            //~ case 'attribute_7' : 
                //~ if(formData[i].value == '') {
                    //~ alert( $('div.misc .alert5').html() );
                    //~ return false;
                //~ }
            //~ break;
            case 'type_of_industry_dp_1' : 
                if(formData[i].value == '') {
                    alert( $('div.misc .alert4').html() );
                    return false;
                }
            break;
            case 'type_of_industry_dp_2' : 
                if(formData[i].value == '----') {
                    alert( $('div.misc .alert4').html() );
                    return false;
                }
            break;
            case 'attribute_16' : 
                if(formData[i].value == '----') {
                    alert( $('div.misc .alert4').html() );
                    return false;
                }
            break;
        }
    }
    addPreloader();
    return true; 
}
// show preloader image
function addPreloader()
{ 
   $('div.main-content').append('<div class="preloader"></div>'); 
}

//validate fullname two words
function isValidFullname(strName){
    //validRegExp =/^([A-Za-z][^\s])+\s([^\s][A-Za-z])$/;

    //validRegExp =/^([A-Za-z])+\t\n\r([A-Za-z])*$/;
    
    // search fullname text for regular exp matches
    //if (strName.search(validRegExp) == -1) 
    //{
    //    return false;
    //} 
    //return true; 
    
    var validRegExp =/^([A-Za-z])$/;
    if (validRegExp.test(strName)) 
    {
         return false;
    } 
    
    //~ var xsplitname = strName.split(" ");

    //~ if(!(xsplitname.length==1))
    //~ {
         //~ return false;
    //~ }
    return true;
    
    
}


// validate email 
function isValidEmail(strEmail){
    validRegExp =/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,3})$/;

    // search email text for regular exp matches
    if (strEmail.search(validRegExp) == -1) 
    {
        return false;
    } 
    return true; 
}

// post-submit callback 
function submitSuccessCallback(responseText, statusText, xhr, $form)
{
 
    $('div.main-content').find('.preloader').remove();
    //alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\n.');  
    if(responseText.success == 'success') {
        // success
        if(responseText.userExist == true)
        {
            //$('#userexist').html("Your profile has been changed.");
            
            $('#new').css("display","none");
            $('#update').css("display","");
        }else
        {
            $('#new').css("display","");
            $('#update').css("display","none");
            //$('#userexist').html("Thank you for signing up");
        }
        slideto(6);
    } else {
        // failed
        alert('An error has been encountered while sending your data. Please try again.');
    }
    
   // alert(responseText);
}

function slideto(num)
{
    var sliderPageHeight = 345;
    var temp;
    
    if(num == 1) {
        $('.button002').removeClass('etSubscriberDetailsSubmit');
        $('.button002').removeClass('page-3-btn');
        $('.button002').addClass('page-2-btn');
        temp = $('.button002').attr('text1');
        $('.button002').attr('value',temp);
    }
    if(num == 2) {
        $('.button002').removeClass('page-2-btn');
        $('.button002').addClass('page-3-btn');
        temp = $('.button002').attr('text1');
        $('.button002').attr('value',temp);
        
    } 
    if(num == 3) {
        $('.button002').addClass('etSubscriberDetailsSubmit');
        $('.button002').removeClass('page-3-btn');
        temp = $('.button002').attr('text2');
        $('.button002').attr('value',temp);
    } 
    if(num==6)
    {
        $('.button002').removeClass('etSubscriberDetailsSubmit');
    }
    
            
    $('#slider').animate({
		'marginTop' : sliderPageHeight - (sliderPageHeight * num)
	});      
	
	
	$('.breadcrumbs .box').each(function(){
        $(this).removeClass('page-btn-selected');
    });
    
    $('.page-'+num+'-btn').addClass('page-btn-selected');
	     
}

function initializeSliderBtn()
{
    // set page slider to page 1
    $('.page-1-btn').addClass('page-btn-selected');
    slideto(1);
    
    $('div.breadcrumbs .box').live('click', function(){
        // unselect all other boxes
        $('div.breadcrumbs').find('.box').each(function(){
            $(this).removeClass('page-btn-selected');    
        });
        // select click box
        $(this).addClass('page-btn-selected');     
    });
}

function handleCheckboxes()
 {
    $('.option-container').find('input.checkbox').each(function(){
        if($(this).attr('checked')) {
            $(this).parent().find('div.option-checked-green').remove();
            $(this).parent().append('<div class="option-checked-green"></div>');
            $(this).parent().parent().addClass('option-selected');
        } else {
            $(this).parent().find('div.option-checked-green').remove();
            $(this).parent().parent().removeClass('option-selected');
        }
    });
    handleLifeSciences();
    handleBreadcrumbs();
}

function handleLifeSciences() 
{
    $('input[name="attribute_32"]').parent().parent().removeClass('option-container-disabled').addClass('option-container');    
         if($('input[name="attribute_32"]').attr('checked'))
         {
            $('input[name="attribute_32"]').parent().find('div.option-checked-green').remove();
            $('input[name="attribute_32"]').parent().append('<div class="option-checked-green"></div>');
            $('input[name="attribute_32"]').parent().parent().addClass('option-selected');
         }
    //~ if($('.option-container').find('[name="attribute_2"]').attr('checked')){
         //~ $('input[name="attribute_32"]').parent().parent().removeClass('option-container-disabled').addClass('option-container');    
         //~ if($('input[name="attribute_32"]').attr('checked'))
         //~ {
            //~ $('input[name="attribute_32"]').parent().find('div.option-checked-green').remove();
            //~ $('input[name="attribute_32"]').parent().append('<div class="option-checked-green"></div>');
            //~ $('input[name="attribute_32"]').parent().parent().addClass('option-selected');
         //~ }
        
    //~ } else {
        //~ $('input[name="attribute_32"]').parent().parent().removeClass('option-container').addClass('option-container-disabled');
        //~ $('input[name="attribute_32"]').parent().parent().removeClass('option-selected');
        //~ $('input[name="attribute_32"]').attr('checked',false);
        //~ $('input[name="attribute_32"]').parent().find('div.option-checked-green').remove();
    //~ }  
   
}

function handleBreadcrumbs() 
{
    
    if($('input[name="attribute_2"]').attr('checked') || $('input[name="attribute_3"]').attr('checked') || $('input[name="attribute_4"]').attr('checked')) {
        // navigating through pages is enabled
        $('div.breadcrumbs').find('div.page-2-btn').removeClass('box-disabled').addClass('box');      
        $('div.breadcrumbs').find('div.page-3-btn').removeClass('box-disabled').addClass('box');
        // manage nav button
        $('.button004').addClass('button002');
        $('.button004').addClass('page-2-btn');
        $('.button004').removeClass('button004'); 
    } else {  
        // navigating through pages is disabled
        $('div.breadcrumbs').find('div.page-2-btn').removeClass('box').addClass('box-disabled');     
        $('div.breadcrumbs').find('div.page-3-btn').removeClass('box').addClass('box-disabled'); 
        // manage nav button      
        $('.button002').addClass('button004');
        $('.button002').removeClass('page-2-btn');
        $('.button002').removeClass('button002');
        slideto(1);       
    }
    
}

function handleSelectBoxes()
{
    var overlayStyle = {
            'position' : 'absolute',
            'top' : '0px',
            'left' : '0px',
            'z-index' : '0',
            'padding' : '3px',
            'overflow' : 'hidden',
            'height' : '10px',
            'width': '250px'
        };
    
    var selectbox = $('select.selectbox');
        
        selectbox.each(function(){
        var thisVal = $(this).find('option[value="'+$(this).val()+'"]').html();
        var thisParent = $(this).parent();
        
        // make sure no overlay exists
        thisParent.find('.selectbox-overlay').remove();
        // add overlay 
        thisParent.append('<div class="selectbox-overlay"></div>');
        thisParent.find('.selectbox-overlay').html(thisVal);
        // style the overlay
        thisParent.find('.selectbox-overlay').css(overlayStyle);
        thisParent.css({'position':'relative'});
    });
    
}

function handle_type_of_industry_dp_1()
{
    var val = $('select[name="type_of_industry_dp_1"]').val();          
    
    addPreloader();
    $.post('lib/manage-selectbox.php', {'type_of_industry_dp_1' : val}, function(data){
        if(data != '') {
            $('select[name="type_of_industry_dp_2"]').html(data);
            handleSelectBoxes();
            $('div.main-content').find('.preloader').remove();
        }
    });
    
    handleProfile(); 
    
}

function handleProfile() 
{
    var val = $('select[name="type_of_industry_dp_1"]').val();
    addPreloader();
    $.post('lib/manage-profile-selectbox.php', {'type_of_industry_dp_1' : val}, function(data){
        if(data != '') {
            $('select[name="attribute_16"]').html(data); //alert(data);
            handleSelectBoxes();
            $('div.main-content').find('.preloader').remove();
        }
    });
}

function handleHelpOptions()
{  
    $('.help-option').live('mouseenter', function(){
        var faqData = $(this).attr('connectwith');
        $('.' + faqData).show();
        $(this).css({'position' : 'relative', 'z-index' : '200'});
    }).live('mouseleave', function(){
        var faqData = $(this).attr('connectwith');
        $('.' + faqData).hide();
        $(this).css({'position' : 'relative', 'z-index' : '0'});
    });
}

