$(function(){
    visit_count = 0;
    if(readCookie('visit')){
        visit_count = parseInt(readCookie('visit'));
    }
    visit_count++;
    createCookie('visit',visit_count,7);
    
    $('div#PhoneFlagListBg dl dt a, img.arrw').click(function(){
        var status=$('#PhoneFlagListBg').hasClass('closed') ? 'open' : 'closed';
        $('#PhoneFlagListBg').get(0).className = $('#PhoneFlagListBg').hasClass('closed') ? 'open' : 'closed';
        $('.flagCntnr').bind('clickoutside',function(){
            $('#PhoneFlagListBg').get(0).className = 'closed';
        });
    })
    $('#PhoneFlagListBg dl dd a').click(function(){
        $('#PhoneFlagListBg dl dd').removeClass('selected');
        selectFlag(this);
    });
});

function selectFlag(el){
    $(el).parent().addClass('selected');
    $('div.tollFree').text($(el).find('span').html());
	$('#PhoneFlagListBg dl dt a').attr( 
		{'href':$(el).attr('href'),'title':$(el).attr('title')}
	).html(
		'<img src="' + ($(el).find('img').attr('src')) + '" alt="" />'
	);													
	$('#PhoneFlagListBg').get(0).className = 'closed';  

}
function slideSwitch() {
	var $active = $('#slideshow div.active');
	if ( $active.length == 0 ) $active = $('#slideshow div:last');
	var $next =  $active.next().length ? $active.next(): $('#slideshow div:first');
	$active.addClass('last-active');
	$next.css({opacity: 0.0})
	.addClass('active')
	.animate({opacity: 1.0}, 1000, function() {
		$active.css('opacity','0');
		$active.removeClass('active last-active');
	});
}
$(function(){$(".megamenu").megamenu({enable_js_shadow:true});
	$('div.orMenu > div.orMenuWrap').click(function() {
		var $lefty = $(this);
		$lefty.animate({
		  left: parseInt($lefty.css('left'),10) == 0 ?
		-$lefty.outerWidth() :	0
		});
	});
	$('div.orMenu > div.orMenuSelect > a').click(function() {
		var $right = $(this).parent().parent().find('.orMenuWrap');
		console.log($right);
		$right.animate({left:0});
	});
	setInterval( "slideSwitch()", 5000 );
	$("a[rel='fancybox']").fancybox({
	'width'				: '75%',
	'height'			: '75%',
	'autoScale'			: false,
	'transitionIn'		: 'none',
	'transitionOut'		: 'none',
	'type'				: 'iframe',
	 'showNavArrows':false,
	'cyclic':false
	});
});

function validateEmailAddSend(){
    if(document.getElementById('email_send')!=undefined && document.getElementById('email_send').value.length >0) {if(document.getElementById('email_send').value.match(/^\w+(['\.\-\+]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/) == null){
            alert('Not a valid email address');
            document.getElementById('email_send').focus();
            return false;
        }
    }
}

function validate_sendnote(pageName){
    var res = validateEmailAddSend();
    if(res == false){
        return false;
    }
    if(document.getElementById('req_id_send') != null){
        var reqs=document.getElementById('req_id_send').value;
        reqs = reqs.substring(0,reqs.lastIndexOf(';'))
        var req_fields = new Array();
        var req_fields = reqs.split(';');
        nbr_fields = req_fields.length;
        var req = true;
        for(var i=0;i<nbr_fields;i++){
            if(document.getElementById(req_fields[i]).value.length <=0 || document.getElementById(req_fields[i]).value==0){
                req = false;
                document.getElementById(req_fields[i]).focus();
                break;
            }
        }
        if(req){
            if(document.getElementById('description_send').value.length < 25){
                alert('Contact Msg should require 25 characters');
                document.getElementById('description_send').focus();
                return false;
            }else{
                var fullname = $('input#name_send').val();
                var name = fullname.split(/\s+/g);
                $('input#name_send').val(name.shift());
                if((lastname = name.shift())){$('input#lastname').val(lastname);}
                $('input#refpage_send').val(setPage(pageName));
                document.getElementById('sendNoteForm').submit();
                return false;
            }
        }
        else{
            alert('Please provide all the required fields');
            return false;
        }
    }
    return false
}
function setPage(pageName){
    var referringPage = 'Cookie Sessions: ';
    referringPage += readCookie('leadsvisited') + ' - ';
    referringPage += readCookie('bnname') + ' - ';
    referringPage += pageName + ' - ';
    referringPage += window.location;
    return referringPage;
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function startLiveChatWindow(){
    if (LC_Status == ""){
        LC_Status == "offline";
	_gaq.push(['_trackEvent','live-chat','offline']);
    }
    if (LC_Status == 'online'){
	_gaq.push(['_trackEvent','live-chat','online']);
        window.open('https://chat2.livechatinc.com/licence/1070936/open_chat.cgi?groups=0&amp;lang=en'+'&amp;dc='+escape(document.cookie+';l='+document.location+';r='+document.referer+';s='+typeof lc_session),'Czat_1028617','width=529,height=520,resizable=yes,scrollbars=no,status=1');
        return false;
    }else{
	_gaq.push(['_trackEvent','live-chat','leave-message']);
        window.open('http://www.singlehop.com/leads/index_livechatmessage.php','Czat_1028617','width=529,height=670,resizable=yes,scrollbars=no,status=1');
        return false;
    }
}
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/* chat slider section */
$(function(){
    var chat_obj = {persons:[
            {'name':'Adrienne Wicklund','designation':'Account Consultant','work_hours':'9AM - 5PM','image':'Adrienne.png'},
            {'name':'Amanda Mettille','designation':'Account Consultant','work_hours':'9AM - 5PM','image':'amanda.png'},
            {'name':'Cara Mooney','designation':'Sales Consultant','work_hours':'9AM - 5PM','image':'cara.png'},
            {'name':'Chris Larkin','designation':'Senior Sales Consultant','work_hours':'8AM - 4PM','image':'chrislarkin.png'},
            {'name':'Christina Georgi','designation':'Account Consultant','work_hours':'8AM - 4PM','image':'christina.png'},
            {'name':'Jennie Sullivan','designation':'Senior Account Consultant','work_hours':'10AM - 6PM','image':'jennie.png'},
            {'name':'Lynzee Colclasure','designation':'Account Consultant','work_hours':'12PM - 8PM','image':'lynzee.png'},
            {'name':'Martina Mihaljcic','designation':'Senior Sales Consultant','work_hours':'9AM - 5PM','image':'martina.png'},
            {'name':'Miguel Villegas','designation':'Senior Sales Consultant','work_hours':'9AM - 5PM','image':'miguel.png'},
            {'name':'Ryan Quinn','designation':'Senior Sales Consultant','work_hours':'12PM - 8PM','image':'ryanquinn.png'}
        ]
    };
    
    var available_operators = new Array();

    $.each(chat_obj.persons,function(i,person){
      
        w_time = new Array();
        w_time = person.work_hours.split('-');
     
        start_time = w_time[0];
        end_time   = w_time[1];
        var t_pm_regex = new RegExp('PM', "i");
        var t_am_regex = new RegExp('AM',"i");
        
        if(start_time.match(t_pm_regex)){
            start_time = start_time.replace(' ','');
            start_time = parseInt(start_time.replace('PM',''));
            if(start_time != 12){
               start_time += 12;
            }
        }else if(start_time.match(t_am_regex)){
            start_time = start_time.replace(' ','');
            start_time = parseInt(start_time.replace('AM',''));
            if(start_time == 12){
                start_time = 0;
            }
        }
        
        if(end_time.match(t_pm_regex)){
            end_time = end_time.replace(' ','');
            end_time = parseInt(end_time.replace('PM',''));
            if(end_time != 12){
               end_time += 12;
            }
        }else if(end_time.match(t_am_regex)){
            end_time = end_time.replace(' ','');
            end_time = parseInt(end_time.replace('AM',''));
            if(end_time == 12){
                end_time = 24;
            }
        }
        
        
        ct = getTimeZoneObj('Chicago',-6); //Get the chicago timezone val
        //ct = getTimeZoneObj('Mumbai',6); //Get the chicago timezone val
        
        current_c_time = parseInt(ct.getHours());
        if(current_c_time >= start_time && current_c_time <= end_time){available_operators.push(i);}
    });
    var chat_person;
    if(available_operators.length > 0){
        random_index = available_operators[Math.floor(Math.random()*available_operators.length)];
        chat_person = chat_obj.persons[random_index];
    }else{
        chat_person = chat_obj.persons[Math.floor(Math.random()*chat_obj.persons.length)];
    }
    
    $('.chatWindow .details').empty();
    chat_html  = '<img src="http://www.singlehop.com/images/chat/'+chat_person.image+'" alt="'+chat_person.name+'" />'
    chat_html += '<h4>'+chat_person.name+' </h4>';
    chat_html += '<h5>'+chat_person.designation+' </h5>';
    chat_html += '<h4 class="indentTop">Hours</h4>';
    chat_html += '<h5>'+chat_person.work_hours+'</h5>'
    chat_html += '<h5>Mon - Fri</h5>';
    $('.chatWindow .details').html(chat_html);

    var chatwindow = function(){
        $('.chatNow').unbind('click');
        var right_val = $('.chatWindow').css('right').replace('px','');
        
        if(right_val == '0'){
            right_val = '-253';
        }else{
            right_val = $('.chatWindow').css('right').replace('-','');;
        }
       
       $('.chatWindow').animate({
            right: "+=" + right_val
        },1000,function(){$('.chatNow').bind('click',chatwindow);});
    };
    $('.chatNow').click(chatwindow);
    
    $('.chatWindow .close').click(function(){
        right_val = '-253';
        $('.chatWindow').animate({
            right: "+=" + right_val
        },1000);
    });
});
    
function getTimeZoneObj(city, offset) {
    // create Date object for current location
    d = new Date();
    // convert to msec
    // add local time zone offset 
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    // create new Date object for different city
    // using supplied offset
    nd = new Date(utc + (3600000*offset));
    // return time as a string
    return nd;
}

/* End of chat slider section */

/* Starting Leap Login */

function loadlogin(){
    $('#modal').dialog('open');
    //$('.inpcntnr input[type="text"]').blur();
    /*$('input[name="password"]').blur(function(){
        if(this.value == ''){$(this).attr({value:'Password',type:'text'});
        }
    });
    $('input[name="password"]').focus(function(){
           if(this.value == 'Password'){$(this).attr({value:'',type:'password'});
           }
    });*/
    
    $('.login_cntnr input[name="password-txt"]').focus(function(){
        $(this).hide();
        $('.login_cntnr input[name="password"]').show();
        $('.login_cntnr input[name="password"]').focus();
    });
    
    $('.login_cntnr input[name="password"]').blur(function(){
        if(this.value == ''){
            $(this).hide();
            $('.login_cntnr input[name="password-txt"]').show();
            $('.login_cntnr input[name="password-txt"]').attr('value','Password');
        }
    });
    
    /* IE Fix */
    $('.login_cntnr .inpcntnr input[type="text"]').blur(function(){
        if(this.name == 'username' && this.value == ''){$(this).attr({'value':'Username'});
        }else if(this.name == 'firstname' && this.value == ''){
            $(this).attr({'value':'First Name'});
        }else if(this.name == 'lastname' && this.value == ''){
            $(this).attr({'value':'Last Name'});
        }else if(this.name == 'email' && this.value == ''){$(this).attr({'value':'Email'});
        }else if(this.name == 'phone' && this.value == ''){$(this).attr({'value':'Phone'});
        }
    });
    $('.login_cntnr .inpcntnr input[type="text"]').blur();
}

$(function(){
    $('#modal').dialog({
        width: 800,
        modal: true,
        resizable: true,
        autoResize: true,
        autoOpen: false,
        closeText: '',
        show: 'fade',
        hide: 'fade',
        closeOnEscape: false,
        open: function() {
            $('.ui-widget-overlay').hide().fadeIn();
            $('#modal .zoom').addClass('normal');
            $('#modal').parent().css({'background':'none !important','border':'none !important'});
            $('#modal').parent().children(':first-child').css({'display':'none'});
        }
    });
    
    $('#modal .close').click(function() {
        $('#modal').fadeOut();
        $('.ui-widget-overlay').fadeOut(500, function() {
          $('#modal').dialog('close');
          $('#modal .zoom').removeClass('normal');
        });
    });
    
    
    $('input[class="required"]').focus(function(){
        if($(this).val() == $(this).attr('placeholder')){$(this).val('');}
    });
    function leapLogin(){
        var validated = true;
        $('form#leap-login-form input[class="required"]').each(function(){
            var val = $(this).val();
            var placeholder = $(this).attr('placeholder');
            if(val == placeholder || val == ''){
                alert(placeholder + ' is required!');
                $(this).focus();
                validated = false;
                return false;
            }
        });
        if(validated){$('form#leap-login-form').submit();}
    }
    function leapSignup(){
        var validated = true;
        $('form#leap-signup-form input[class="required"]').each(function(){
            var val = $(this).val();
            var placeholder = $(this).attr('placeholder');
            if(val == placeholder || val == ''){
                alert(placeholder + ' is required!');
                $(this).focus();
                validated = false;
                return false;
            }
        });
        if(validated){$('form#leap-signup-form').submit();}
    }
    $('a#leap-login').click(leapLogin);
    $('a#leap-signup').click(leapSignup);
    
    
});

/* End of Leap Login */
