$(function(){
	// Buttons
	$('button, input[type=button], div:not(#navcontainer) > input[type=submit], .button').button();
	
	// Accordian
	$( ".accordion" ).accordion();
	
	// dates
	$('.datebox').datepicker({dateFormat: 'yy-mm-dd'});
	
	// Rate Boxes
	var ratechange = function(){
		var fnd = $(this).val();
		var list = $(this).parent().parent().next().find('tbody tr');
		
		if(fnd == ''){
			list.css('display', 'table-row');
			return;
		}
		
		var list_found = $(this).parent().parent().next().find('tbody tr:Contains(' + fnd + ')');
		list.css('display', 'none');
		list_found.css('display', '');
	}
	
	$('.ratefilter').keyup(ratechange);
	$('.ratefilter').change(ratechange);
	
	// Navigation
	$('#GHR ul li').mouseover(function(){
		// highlight the tab
		$('#GHR ul li.selected').removeClass('selected');
		$(this).addClass('selected');
		
		// show the related sub-item
		$('#Nav ul.visible').removeClass('visible');
		$('#Nav_' + $(this).attr('id')).addClass('visible');
	});
	
	$('#GHR ul li').click(function(){
		window.location = $(this).find('a').attr('href');
	});
	
	$('#Gheader').mouseleave(function(){
		if($('.selected_orig').size() > 0){
			// revert to originals
			$('#GHR ul li.selected').removeClass('selected');
			$('#GHR ul li.selected_orig').addClass('selected');
			
			$('#Nav ul.visible').removeClass('visible');
			$('#Nav ul.selected_orig').addClass('visible');
		}
	});
	
	// main page stuff
	$('#close_popup').click(function(e){
		e.preventDefault();
		$('#popup_banner').css('display', 'none');
	});
	$(window).resize(function() {
		$('#popup_banner').css('left', (($(document).width() / 2) - 150) + 'px');
	});
	$('#popup_banner').css('left', (($(document).width() / 2) - 150) + 'px');
	
	// popup for yak signup
	$('.signup_button').click(function(e){
		e.preventDefault();
		$('object').css('display', 'none');
		
		$( "#signup-dialog-message" ).dialog({
			modal: true,
			width: 650,
			draggable: true,
			buttons: {
				Cancel: function() {
					$( this ).dialog( "close" );
					$('object').css('display', '');
				}
			},
			close: function(){
				$('object').css('display', '');
			}
		});
		
		for(i=0; i<=20; i++){
			if($(this).hasClass( 'p' + LZ(i) ))
				$('#p' + LZ(i)).attr('checked', 'checked');
		}
		
		
		$('#customer_call_but').click(function(e){
			e.preventDefault();
			
			if($('#cust_name').val().length < 2){
				alert("Please enter a valid name");
			}else if($('#cust_name2').val().length < 2){
				alert("Please enter a valid name");
			}else if($('#cust_phone').val().length < 10){
				alert("Please enter a valid phone number");
			}else if($('#cust_email').val().indexOf("@") < 0){
				alert("Please enter a valid email");
			}else{
				$('#customer_call').submit();
			}
		});
	});
	
});

/// image rotator
$(document).ready(function() {	
	setInterval('swapMainImages()', 6000);
});

function swapMainImages(){
	$('#main_rotate_img .active').fadeOut(550, function(){
		var next = $('#main_rotate_img .active').next();
		if(next.length == 0)
			next = $('#main_rotate_img a:first');
			
		$('#main_rotate_img .active').removeClass('active');
		
		next.fadeIn(750).addClass('active')
	});
}

jQuery.expr[':'].Contains = function(a,i,m){
     return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};

$(function(){
	// for tab pages
	// check for existance of tab page
	var pt_ele = $('#product_tabs');
	if(pt_ele.length == 0) return false;
	
	// tab links, find the FAQ link so we know it's tab number
	var tab_links = $('#product_tabs > ul > li > a');
	var faq_link = 0;
	tab_links.each(function(index){ 
		if($(this).html() == 'FAQ' || $(this).attr('href') == '#tab-faq')
			faq_link = index; 
	});
	
	// setup the tab element
	var sel = {};
	if(window.location.hash && window.location.hash.substring(1,4) == 'faq')
		sel = { selected: faq_link };

	var p_tabs = pt_ele.tabs(sel);
	
	tab_links.each(function(index){
		$('a[href=' + $(this).attr('href') + ']').click(function(){
			p_tabs.tabs('select', index);
			return false;
		});
	});
	
	// set the page FAQ links if they exist
	$('a[href^=#faq]').click(function(){
		p_tabs.tabs('select', faq_link);
		
		var x = $(this).attr('href').replace('#', '');
		var tag = $('a[name=' + x + ']');
		
		var st = tag.offset().top - 150;
		$(window).scrollTop( st );
		
		tag.parent().parent().animate({ backgroundColor: "#68BFEF" }, 2000, '', function(){ tag.parent().parent().animate({ backgroundColor: '#F5F5F5' }, 2000); });
		
		return false;
	});
	
	// if the page has a direct faq link
	if(window.location.hash && window.location.hash.substring(1,4) == 'faq')
		$('.faqlist ul li a[href=' + window.location.hash + ']').click();

});

/* email a friend stuff */
$(function(){
	if($('#email_body').length > 0){
		$('#email_subject').val($('#email_sub').html());
		$('#email_content').val($('#email_body').html().replace(/<br>/gi, '\r\n').replace(/<br\/>/gi, '\r\n'));

		$('#editemail').click(function(e){
			e.preventDefault();
			$(this).remove();

			$('#email_edit').css('display', '');
			$('#email_compiled').css('display', 'none');
		});
	}
});


/* 911 account login data */
var account_list = false;

function display_address(login){
	//console.info("display_address");
	
	$.each(account_list, function(index, value){
		if(value.voip_id == $('#voip_login').val()){
			//console.info("address_found", value);
			var address = value.emergencyAddressInfo;
			$('#voip_name').html(address.firstName + " " + address.lastName);
			$('#locNum').val(address.locationNumber1);
			$('#streetNumber').val(address.streetNumber);
			$('#streetNumberSuffix').val(address.streetNumberSuffix);
			$('#streetName').val(address.streetName);
			$('#streetDirection').val(address.streetDirection);
			$('#municipality').val(address.municipality);
			$('#postalCode').val(address.postalCode);
			$('#telephoneDay').val(address.telephoneDay);
			$('#telephoneDayExtension').val(address.telephoneDayExtension);
			
			$('#locTypeOrig').val(address.locationType1);
			//$('#locType').val(address.locationType1);
			
			$('#streetTypeOrig').val(address.streetType);
			//$('#streetType').val(address.streetType);
			
			$('#provOrig').val(address.province);
			$('#province').val(address.province);//console.info(address);
			
			prov_change();
		}
	});
}

function prov_change(){
	//console.info('prov change');
	if($('#province').val() == '' )
		return;
	
	//console.info($('#province option:selected'));
	// street type
	$.get('/AJAX/Get911StreetType/', {'prov': $('#province option:selected').attr('class')}, function(data){
		// do something
		if(data){
			$('#streetType').html('');
			
			$.each(data.Table, function(key, itm){
				//console.info(itm);
				if(itm.StreetType instanceof Object){
					$('#streetType').append('<option></option>');
				}else{
					$('#streetType').append('<option>' + itm.StreetType + '</option>');
				}
			});
			
			$('#streetType').val($('#streetTypeOrig').val());
		}
	});
	
	// location type
	$.get('/AJAX/Get911LocationType/', {'prov': $('#province option:selected').attr('class')}, function(data){
		// do something
		if(data){
			$('#locType').html('');
			
			$.each(data.Table, function(key, itm){
				//console.info(itm);
				if(itm.LocationType instanceof Object){
					$('#locType').append('<option></option>');
				}else{
					$('#locType').append('<option>' + itm.LocationType + '</option>');
				}
			});
			
			$('#locType').val($('#locTypeOrig').val());
		}
	});
};

// Yak Digital 911
$(function(){
	if($('#verifybut')){
	
		$('#province').change(prov_change);
	
		$('#verifybut').click(function(e){
		
				// load the provinces in paralell
				$('#province').html('<option disabled=disabled>Loading</option>');
				$.get('/AJAX/Get911Prov', function(data){
					// do something
					if(data){
						$('#province').html('');
						
						$.each(data.Table, function(key, itm){
							$('#province').append('<option class="'+itm.ProvinceCode+'">' + itm.ProvinceName + '</option>');
						});
						
						if($('#provOrig').val() != '')
							$('#province').val($('#provOrig').val());
							
						prov_change();
					}
				});
		
				//alert("hi");
				e.preventDefault();
				$('#show_error').css('display', 'none');
				$('#verify_but_box').css('display', 'none');
				$('#verify_but_load').css('display', '');
				
				$.post('/AJAX/LookUpAccountList', 
						{login: $('#customer_id').val(), password: $('#customer_password').val()}, 
						function(data){
							
							$('#verify_but_box').css('display', '');
							$('#verify_but_load').css('display', 'none');
								
							if(data.error){
								$('#user_error_content').html(data.error);
								$('#show_error').css('display', '');
							}else{
								$("#verifybox").css('display', 'none');
								$('#login_select').css('display', '');
								$("#address_info").css('display', '');
								$("#customer_id").attr('disabled', 'disabled');
								$("#customer_password").attr('disabled', 'disabled');
								
								account_list = data.result;
								
								$.each(data.result, function(index, value){
									$('#voip_login')
										  .append($("<option></option>")
										  .attr("value",value.voip_id)
										  .text(value.username)); 
								});
								
								//console.info(data);
								
								display_address();
							}
						});
			});
			
		$("#submit_change").click(function(e){
			e.preventDefault();
			
			$("#customer_id").attr('disabled', '');
			$("#customer_password").attr('disabled', '');
			var data = $('#address_form').serialize(); // to get the data while its available for edit
			$("#customer_id").attr('disabled', 'disabled');
			$("#customer_password").attr('disabled', 'disabled');
			
			$('#submit_but_box').css('display', 'none');
			$('#submit_but_load').css('display', '');
			
			$.post('/AJAX/Set911Info', 
					data, 
					function(data){
						//console.info(data);
			
						if(data.error){
							$('#user_error_content').html(data.error);
							$('#show_error').css('display', '');
							
							$('#submit_but_box').css('display', '');
							$('#submit_but_load').css('display', 'none');
							
						}else{
							$( "#dialog-message" ).dialog({
								modal: true,
								buttons: {
									Ok: function() {
										window.location = "http://yak.ca/";
										//$( this ).dialog( "close" );
									}
								}
							});
						}
							
					});
		});
		
		$("#address_form").submit(function(e){
			e.preventDefault();
		});
			
		$('#voip_login').change(display_address);
	}
});

function LZ(x) {return(x<0||x>9?"":"0")+x}

// Portal stuff
$(function(){
	$('#refer_a_friend').click(function(e){
		e.preventDefault();
		$("#dialog-ref").dialog({
				resizable: false,
				width: 410,
				modal: true,
				buttons: {
					'Send': function() {
						$(this).dialog('close');
					},
					Cancel: function() {
						$(this).dialog('close');
					}
				}
			});
		});
	
	$('#add_more').click(function(){
		$('#refer_box').append("<tr>"+
			'	<td><input type="text" id="new_email" value="" style="width: 20em;" /></td>'+
			"</tr>");
	});
	
	$('.change_address').click(function(e){
		e.preventDefault();
		$("#dialog-address").dialog({
				resizable: false,
				width: 500,
				modal: true,
				buttons: {
					'OK': function() {
						$(this).dialog('close');
					}
				}
			});
	});

	$('.change_payment-method').click(function(e){
		e.preventDefault();
		$("#dialog-address").dialog({
				resizable: false,
				width: 500,
				modal: true,
				buttons: {
					'OK': function() {
						$('#ccform2').submit();
					},
					'Cancel': function() {
						$(this).dialog('close');
					}
				}
			});
	});

	$('.change_creditcard').click(function(e){
		e.preventDefault();
		$("#dialog-creditcard").dialog({
				resizable: false,
				width: 500,
				modal: true,
				buttons: {
					'OK': function() {
						$('#ccform').submit();
					},
					'Cancel': function() {
						$(this).dialog('close');
					}
				}
			});
	});
	
	$('.change_password').click(function(e){
		// display the box, have it slide out
		e.preventDefault();
		$(this).parent().css('display', 'none');
		$('#change_password').slideDown(300);
	});

	$('.change_email').click(function(e){
		// display the box, have it slide out
		e.preventDefault();
		$(this).parent().css('display', 'none');
		$('#change_email').slideDown(300);
	});
	
	var submitting_payment = false;
	$('#make_payment').click(function(e){
		e.preventDefault();
		var error = false;
		
		if($('#cardno').val() == ''){
			error = "Please fill out a card number";
		}else if($('#cardname').val() == ''){
			error = "Please fill out your name";
		}else if($('#expiry1').val() == '' || $('#expiry2').val() == ''){
			error = "Please fill out your card expiry";
		}else if($('#cvv').val() == ''){
			error = "Please fill out the CVV for your credit card";
		}else if($('#address').val() == ''){
			error = "Please fill out your address";
		}else if($('#city').val() == ''){
			error = "Please fill out your address";
		}else if($('#postal').val() == ''){
			error = "Please fill out your address";
		}else if($('#payment').val() == '' || parseFloat($('#payment').val()) <= 0){
			error = "Please enter an amount greater then $0.00";
		}else if(parseFloat($('#payment').val()) <= 5 && parseFloat($('#payment').val()) <= parseFloat($("#balance").val())){
			error = "You must pay a minimum of $5 or your balance (whichever is lower)";
		}
		
		if(error){
			$("#js_error").html(error);
			
			$( "#dialog-message" ).dialog({
				modal: true,
				buttons: {
					Ok: function() {
						$( this ).dialog( "close" );
					}
				}
			});
		}
		
		if(!error && !submitting_payment){
			$('#payment_form').submit();
			submitting_payment = true;
			$(this).attr("disabled", "disabled");
		}
	});
	
	$('#add_service').click(function(){window.location = 'http://yak.ca'});
	
	$('.calendar').datepicker();
	
	// Yak Digital Manage Number
	$('#managing').change(function(){
		window.location = '/yak_digital/?page=' + $('#managingpage').val() + '&number=' + $('#managing').val();
	});

	// Yak digital handler
	function run_digital(){
		$('#yakdigital_container').addClass('ui-tabs ui-widget ui-widget-content ui-corner-all');
		$('#yakdigital_container>ul').addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
		$('#yakdigital_container>ul>li').addClass('ui-state-default ui-corner-top');
		$('#yakdigital_container>ul>li').mouseover(function(){ $(this).addClass('ui-state-hover'); });
		$('#yakdigital_container>ul>li').mouseout(function(){ $(this).removeClass('ui-state-hover'); });
		$('#yakdigital_container>ul>li.selected').addClass('ui-tabs-selected ui-state-active');
		$('#yakdigital_container>div').addClass('ui-tabs-panel ui-widget-content ui-corner-bottom');
	}; run_digital();
});

// konami code
if ( window.addEventListener ) {  
  var state = 0, konami = [38,38,40,40,37,39,37,39,66,65];  
  window.addEventListener("keydown", function(e) {  
    if ( e.keyCode == konami[state] ) state++;  
    else state = 0;  
    if ( state == 10 )  
      $('.konami').css('display', ''); 
    }, true);  
}  
