// ================ 
// ! Onload Event   
// ================ 


$(document).ready(function(){
	/* Load global logic (header/footer/nav stuff) */
	global_loader();
	
	var loc = window.location.pathname;
	
	/* If we're on a p3 page */
	if (loc.substr(0,4) == '/p3/') {
		p3_loader();
	}
	/* search page */
	else if (loc.substr(0,8) == '/search/') {
		search_loader();
	}
	/* front page */
	else if (loc == '/' || loc == '/index.php') {
		frontpage_loader();
	}
	/* help pages */
	else if (loc.substr(0, 9) == '/helppgs/') {
		help_loader();
	}
	/* Login Page */
	else if (loc == '/secure/login.php') {
		login_page_loader();
	}
	else if (loc.substr(0,10) == '/checkout/') {
		checkout_loader();
	}
	else if (loc == '/giftcard/balance.php') {
		giftcard_balance_loader();
	}
});

// =========== 
// ! Loaders   
// =========== 

function global_loader() {
	/* Create mouseover and mouseout events for top menu categories. Edit: #h_cslink is the customer service link, we don't want that as a category now. */
	$('.h_navcat').mouseover(function(){
		/* If we have a close menu timer running, terminate it. */
		if (typeof window.closeMenuTimer != 'undefined') clearTimeout(window.closeMenuTimer);
		
		/* Used in open_menu() */
		window.currentMenu = this;
		
		/* If a menu was already open, immediately open the new one. */
		if (close_menus() > 0) open_menu();
		/* If none were open, set timer to open current (prevents accidental menu opening) */
		else window.openMenuTimer = setTimeout('open_menu()', 150);
			
	}).mouseout(function(){
		/* Stop any ticking open timers and start up the close menu timer. */
		clearTimeout(window.openMenuTimer);
		window.closeMenuTimer = setTimeout('close_menus()', 350);
	});
	
	/* over and out events for the top menu drop down box */
	$('.h_navdrop').mouseover(function(){
		if (typeof window.closeMenuTimer != 'undefined') clearTimeout(window.closeMenuTimer);
	}).mouseout(function(){
		window.closeMenuTimer = setTimeout('close_menus()', 350);
	});
	
	/* Bind event handler to search button click. */
	$('#h_search > input[type=image]').click(function(){
		if ($('#h_searchfield').val() == "") {
			//alert('Please enter a search term.');
			$('#h_searchfield').focus();
			return false;
		}
		
		window.location = 'http://www.gifttree.com/search/?q='+encodeURIComponent($('#h_searchfield').val());
	});
		
	/* Catch return keys and send to search button. */
	$('#h_searchfield').keypress(function(ev){
		if (ev.keyCode == 13) $(this).next().click();
	});
	
	/* Create event listener for the footer email signup */
	$('#f_emailoffers > input[type=image]').click(function(){
		var email_field = $(this).prev();
		if (valid_email(email_field.val())) {
			$(this).parent().load('/global/gifttree/ajax_listeners/footer_signup_widget.php?email='+email_field.val());
		}
		else {
			alert('Please enter a valid email.');
			email_field.focus();
		}
	});
	
	/* Catch return keys in footer email signup and send it to the submit button */
	$('#f_emailoffers > input[type=text]').keypress(function(ev){
		if (ev.keyCode == 13) $(this).next().click();
	}).focus(function(){ //remove the placeholder on focus
		if ($(this).val() == 'Special Offers Email') this.value = '';
	});
	
	/* Rollover event for city link in footer: */
	$('#f_citylistlink > a').mouseover(function(){
		if (typeof window.cityMouseTimer != 'undefined') clearTimeout(window.cityMouseTimer);
		
		$('.f_dropdown').hide(); //hide footer dropdowns
		
		$('#f_citylist').show().css({
			top: ($('#f_citylistlink').offset().top - $('#f_citylist').height() - 22),
			right: 0
		});
	}).mouseout(function(){
		window.cityMouseTimer = setTimeout("$('#f_citylist').hide()", 500);
	});
	
	$('#f_citylist').mouseover(function(){
		if (typeof window.cityMouseTimer != 'undefined') clearTimeout(window.cityMouseTimer);
	}).mouseout(function(){
		window.cityMouseTimer = setTimeout("$('#f_citylist').hide()", 500);
	});
	
	/* Rollover for directory link in footer */
	$('#f_directorylistlink > a').mouseover(function(){
		if (typeof window.dirMouseTimer != 'undefined') clearTimeout(window.dirMouseTimer);
		
		$('.f_dropdown').hide(); //hide footer dropdowns
		
		$('#f_directorylist').show().css({
			top: ($('#f_directorylistlink').offset().top - $('#f_directorylist').height() - 22),
			right: '60px'
		});
	}).mouseout(function(){
		window.dirMouseTimer = setTimeout("$('#f_directorylist').hide()", 500);
	});
	
	$('#f_directorylist').mouseover(function(){
		if (typeof window.dirMouseTimer != 'undefined') clearTimeout(window.dirMouseTimer);
	}).mouseout(function(){
		window.dirMouseTimer = setTimeout("$('#f_directorylist').hide()", 500);
	});	
}

function p3_loader() {
	/* Build The info tabs. */
	
	var tabs = $('.p3_infotabs_header:visible');
	var tab_count = tabs.length;
	var total_width = $('#p3_infotabs').width();
	tabs.css('width', Math.floor(total_width / tab_count) - 1);
	
	$('.p3_infotabs_header:first-child').css({
		'border-left': 0,
		'width': $('.p3_infotabs_header:first-child').width() + tab_count - 1
	});
	
	/* Add event listeners for tab headers. */
	$('.p3_infotabs_header').click(function(){
		$('.p3_infotabs_header').css('background', 'url("/global/gifttree/images/widgets/desc_gradient_off.gif") repeat-x');
		$(this).css('background', 'url("/global/gifttree/images/widgets/desc_gradient_on.gif") repeat-x');
		
		$('#p3_infotabs_target').html( $('.p3_infotabs_body[parent_tab='+$(this).attr('tab')+']').html() );
	});
	
	/* Click first tab. */
	$('.p3_infotabs_header:first-child').click();
	
	/* Lightbox for alt images. */
	$('#p3_altimages > div > a').lightbox();
	
	/* Check main image size, if small size, remove enlarge image button, else, bind click function to it. */
	if ($('#p3_mainimage > a > img').attr('src').indexOf(/large350/) < 0 && $('#p3_mainimage > a > img').attr('src').indexOf(/gt_large/) < 0) {
		
		/* Remove enlarge button. */
		$('#p3_enlargeimage').remove();
		
		/* Fix some CSS */
		$('#p3_mainimage > a').css('cursor', 'default');
	} 
	else {
		/* Main Image Lightbox: */
		$('#p3_mainimage > a').lightbox();
		
		/* Event handler for enlarge image button */
		$('#p3_enlargeimage').click(function(){
			$('#p3_mainimage > a').click();
		});	
	}
	
	/* Bind event handler for quantity question mark. */
	$('#p3_quantitylabel > img').click(function(){ load_modal('/global/modals/quantity.php'); });
	
	/* Bind event handler for zip code question mark. */
	$('#p3_ziplabel > img').click(function(){ load_modal('/global/modals/zip_finder.php'); });
	
	/* If a quantity is typed that is greater than 1 */
	$('#p3_quantityfield').keyup(function(){
		if ($(this).val() > 1) {
			/* Turn quantity > 1 explanation to red. */
			$('#p3_formexplain > span').css('color', 'red');
			
			/* Disabled the google checkout button. */
			$('#p3_googlebutton > input')
				.attr({
					src: 'http://checkout.google.com/buttons/checkout.gif?merchant_id=765421517435431&w=160&h=43&style=white&variant=disabled&loc=en_US',
					disabled: 'disabled'
				})
				.css('cursor', 'default');
		}
		else {
			/* Turns quantity > 1 explanation back to black. */
			$('#p3_formexplain > span').css('color', 'black');
			
			/* Re-activates google checkout. */
			$('#p3_googlebutton > input')
				.attr({
					src: 'http://checkout.google.com/buttons/checkout.gif?merchant_id=765421517435431&w=160&h=43&style=white&variant=text&loc=en_US',
					disabled: ''
				})
				.css('cursor', 'pointer');
		}
	});
	
	/* Activate button for perz interface. */
	$('#p3_perznote').click(function(){ persInterface('show'); });
	
	/* Check query string in case a zip was rejected and the customer had personalizations. */
	var query_vars = window.location.queryVars();
	var perz_nest = $('#pers_forms');

	for (i in query_vars) {
		var name = i;
		var value = query_vars[i];
		
		if (!/pers_name/.test(name)) continue;
		
		var prod_name = decodeURIComponent(value);
		var prod_id = name.replace(/[\D]+/g, '');
		
		var prod_price = query_vars['pers_price['+prod_id+']'];
		
		var line = 1;
		while (typeof query_vars['pers['+prod_id+']['+line+']'] != 'undefined') {
			var line_value = query_vars['pers['+prod_id+']['+line+']'].replace('\\', '');
			line_value = decodeURIComponent(line_value);
			perz_nest.append('<input type="hidden" piid="'+prod_id+'" prodName="'+prod_name+'" prodPrice="'+prod_price+'" name="pers['+prod_id+']['+line+']" value="'+line_value+'"/>');
			line++;
		}
	}
	
	/* Check to see if we've been passed a hash. */
	if (window.location.hash != "") {
		var tab_num = window.location.hashVars()['tab'];
		if (!isNaN(tab_num)) {
			$('.p3_infotabs_header[tab='+tab_num+']').click();
		}
		
		if (!isNaN(window.location.hashVars()['pviid'])) {
			$('#p3_itemlist > li').not($('#'+window.location.hashVars()['pviid']).parent().parent()).remove();
			$('#'+window.location.hashVars()['pviid']).attr('checked', 'checked');
		}
	}
}

function search_loader() {
	$('#v3_searchbutton > input').click(function(){
		$(this).parent().parent().submit();
		return false;
	});
	
	$('#v3_search > input, #v3_minprice > input, #v3_maxprice > input').keypress(function(ev){
		if (ev.keyCode == 13) $('#v3_searchbutton > input').click();
	});
}

function frontpage_loader() {
	/* Cycler */
	$('#fr_cycler > a').cycle({
		after: function() {
			$(this).parent().attr('href', $(this).attr('url'));
		},
		timeout: 7000,
		pause: true
	});
}

function help_loader() {
	$('#help_sidebar').css('height', $('#body').height());
}

function login_page_loader() {
	if ($('#login_email').val() == "") {
		$('#login_email').focus();
	}
	else {
		$('#login_password').focus();
	}
}

function checkout_loader() {
	$('#co_securitycodemodal').click(function(){
		load_modal('/global/modals/card_security_code.php');
		return false;
	});
	
	if (window.location.pathname == '/checkout/checkout.giftcard.php') {
		$('[name=message]').blur(function(){
			$.get(
				'/checkout/dynamic_updater.php',
				{
					'line': window.location.queryVars()['line'],
					'cart_hash': window.location.queryVars()['cart_hash'],
					'message': $(this).val()
				}
			);
		});
	}
}

function giftcard_balance_loader() {
	$('#gc_balancesubmit').click(function(){
		$('#gc_balanceresults').load('/global/gifttree/ajax_listeners/gc_balance.php?number='+$('#gc_balancecard').val());
	});
	
	$('#gc_balancecard').keypress(function(ev){
		if (ev.keyCode == 13) $('#gc_balancesubmit').click();
	});
	
	$('#gc_balancecard').focus();
}

// ===================== 
// ! Various Functions   
// ===================== 

function close_menus() {
	window.menuTimer = false;
	
	$('.h_navcat')	
		.css({
			'border-width': 0,
			'background': '',
			'color': 'white',
			'padding': '9px 17px 0'
		})
		.children('img').css({
			'visibility': 'visible'
		});

	//if we're using ie6, show the select menus that were previously hidden when the nav opened
	if (is_ie6()) $('select').css('visibility', 'visible');
	
	var open_menu_count = $('.h_navdrop:visible').length;
	$('.h_navdrop').hide();
	return open_menu_count;
}

function open_menu() {
	//ie6 will have select menus show through absolutely positioned elements above them			
	if (is_ie6()) $('select').css('visibility', 'hidden');

	$(window.currentMenu).css({
		'border-color': '#676767',
		'border-style': 'solid',
		'border-width': '1px 4px 0 1px',
		
		'background': 'white',
		'color': 'black',
		'padding-right': 13,
		'padding-left': 16,
		'padding-top': 8
	})
	.next().filter('.h_navdrop').css({
		top: $(window.currentMenu).position().top + 31,
		left:  $(window.currentMenu).position().left
	}).show();
	
	$(window.currentMenu).children('img').css('visibility', 'hidden');
}

function is_ie6() { return /MSIE 6/.test(window.navigator.userAgent); }
function is_ie7() { return /MSIE 7/.test(window.navigator.userAgent); }


/* window.location upgrades */
window.location.queryVars = function() {
	var query = this.search.substr(1);
	
	var query_vars = query.split('&');
	var query_hash_table = [];
	for (var i = 0; i < query_vars.length; i++) {
		var key_val = query_vars[i].split('=');
		query_hash_table[key_val[0]] = key_val[1];
	}
	
	return query_hash_table;
}

window.location.hashVars = function() {
	var hash = this.hash.substr(1);
	
	var hash_vars = hash.split('&');
	var hash_hash_table = [];
	for (var i = 0; i < hash_vars.length; i++) {
		var key_val = hash_vars[i].split('=');
		hash_hash_table[key_val[0]] = key_val[1];
	}
	
	return hash_hash_table;
}

window.location.isSecure = function() { return (this.protocol == 'https:'); }
window.location.dirName = function(dir_level) { return window.location.pathname.split('/')[dir_level]; }
window.location.fileName = window.location.dirName( window.location.pathname.split('/').length - 1 );


/* Modal Logic */
function zip_finder() {
	var address = $('#modal_zf_address').val();
	var city = $('#modal_zf_city').val();
	var state = $('#modal_zf_state').val();
	
	$.get(
		'/global/modals/zip_finder.php?address='+address+'&city='+city+'&state='+state,
		function(data){
			data = $.trim(data);
			if (data == 'blank_info') alert("Please fill in all of the forms.");
			else if (data == 'not_found') {
				var show_string = 'Not found.';
			}
			else if (!isNaN(data)) {
				var show_string = data;
			}
			else alert("An error occured, please try again.");
		
			if (typeof show_string != "undefined") {
				$('#modal_zf_results').slideDown().children('strong').html(show_string);
			}
		}
	);
}

function load_modal(modal_url, exit_function) {
	//create background shade
	var shade = modal_shade();
	
	//add content div to the dom
	$('body').prepend('<div id="modal_content" style="position: absolute;"></div>');

	//make it invisible, inject the remote modal markup into it, then fade it in
	$('#modal_content').css({
		'visibility'		: 'hidden',
		'opacity'			: 0
	}).load(modal_url, null, function(){
		//ie6 doesn't like position fixed, so just use absolute:
		if (is_ie6()) $(this).css('position', 'absolute');
		else $(this).css('position', 'fixed');

		$(this).css({
			'left'			: '50%',
			'top'			: (window.innerHeight || document.documentElement.clientHeight)/2,
			'background'	: 'white',
			'z-index'		: '1001',
			'visibility'	: 'visible',
			'margin-left'	: ($(this).width()/-2) -3,
			'margin-top'	: ($(this).height()/-2) -3,
			'border'		: '3px solid #BFBFBF'
		}).animate({ opacity: 1 }, 'fast');
	});
	
	//give the background shade click instructions:
	$(shade).click(function(){
		$('#modal_content').animate({ opacity: 0 }, function() { $(this).remove(); });
		$(this).animate({ opacity: 0 }, function() { $(this).remove(); });
		
		if (typeof exit_function == 'function') exit_function();
		else if (typeof exit_function == 'string') window.location = exit_function;
	});
}

function modal_shade(destroyFlag) {
	if (typeof destroyFlag != 'undefined' && destroyFlag == 'destroy') {
		$('#modal_shade').remove();
		return;
	}
	
	$('#modal_shade').remove();

	$('body').prepend('<div id="modal_shade"></div>');
	
	if (!isNaN(window.scrollMaxY)) var height = window.innerHeight + window.scrollMaxY;
	else if (!isNaN(document.height)) var height = document.height;
	else if (!isNaN(document.documentElement.scrollHeight)) var height = document.documentElement.scrollHeight;
	else var height = '100%';
	
	$('#modal_shade').css({
		'position'		: 'absolute',
		'left'			: '0',
		'top'			: '0',
		'width'			: '100%',
		'height'		: height,
		'opacity'		: '0',
		'z-index'		: '1000',
		'background'	: 'black'
	}).animate({ opacity: 0.85 }, 'slow');
	
	return $('#modal_shade')[0];
}

function tell_friend(bpid, version) {	
	$.post(
		'/global/modals/tell_a_friend.php',
		{
			'bpid': bpid,
			'version': version,
			'f_n': $('#modal_taf_friend_name').val(),
			'f_e': $('#modal_taf_friend_email').val(),
			'y_n': $('#modal_taf_your_name').val(),
			'y_e': $('#modal_taf_your_email').val(),
			'msg': $('#modal_taf_your_message').val(),
			'e_m': $('#modal_taf_email_me').is(':checked')
		},
		function(data) {
			if (data == 'success') {
				$('#modal_taf_forms').slideUp('slow');
				$('#modal_taf_success').slideDown('slow');
			}
			else if (data == 'incomplete') {
				alert('Some of the fields were left incomplete or are invalid.');
			}
			else {
				alert('Email could not be sent, please try again.');
			}
		}
	);
}

function live_chat() {
	window.open('https://server.iad.liveperson.net/hc/55872508/?cmd=file&amp;file=visitorWantsToChat&amp;site=55872508&amp;imageUrl=https://www.gifttree.com/globalimages/logo.gif&amp;referrer='+escape(document.location),'chat55872508','width=472,height=320,resizable=yes');
	window.location = window.location.toString();
	return false;
}

function log(obj) { if (window.console) window.console.log(obj); }
function tag_dump(selector) { $(selector).each(function(){ log(this); }); }

(
	function($) {
		$.fn.log = function() {
			return this.each(function(){ window.console.log(this); });
		}
	}	
)(jQuery);

function ajaxCall() { return; }

function valid_email(email) {
	var check = /^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
	return check.test(email);
}



