// Karen Caldwell Design
// Written by Nic Hubbard - Zed Said Studio
// http://www.zedsaid.com

$(document).ready(function() {

	// Globals
	var slide_interval, check_images, images_loaded = false, slide_time = 6000, glob_index = 100, id = 1000, use_child = false, curr_scroll, info_url, in_ajax = false, in_scroll = false, clickedID = 0;
	
	// Main Navigation
	$('div.mainItems').click(function() {
		clickedID = clean_id($(this).attr('id'));
		//console.log(clickedID);
	});
	
	// ----- Get rid of IE6!! -----
	if (typeof worst_browser_ever !== 'undefined') {
		if (worst_browser_ever) {
			var msg = 'You are using Internet Explorer version 6.0 or lower. Due to security issues and lack of support for Web Standards it is highly recommended that you upgrade to a ';
			$('body').prepend('<div id="noIE" style="display:none">'+msg+'<a target="_blank" href="http://www.mozilla.com/firefox/">modern browser</a>.</div>');
			$('#noIE').slideDown('slow');
			setTimeout(function() {
				$('#noIE').slideUp('slow');		
			}, 20000);
		}//end if
	}//end if
	
	// ##### Custom Functions #####
	// Function to run scrolling
	function applyScroll(obj) {
		obj.parent().append('<div class="scrollingTop"></div><div class="scrollingBottom"></div>');
		// Get our height
		var img_height = obj.children('img').attr('height');
		// Bind events
		$('div.scrollingBottom').mouseenter(function() {
			if (!in_scroll) {
				setTimeout(function() {
					in_scroll = true;
					obj.scrollTo(img_height, {
						duration: 4000, 
						onAfter: function() {
							in_scroll = false;												   
					   }
				   });//end scrollTo									  
				}, 1000);
			}//end if
		});
		$('div.scrollingTop').mouseenter(function() {
			if (!in_scroll) {
				setTimeout(function() {
					in_scroll = true;
					obj.scrollTo('0px', {
						duration: 4000, 
						onAfter: function() {
							in_scroll = false;												   
					   }
					});//end scrollTo
				}, 1000);
			}//end if
		});

	}//end applyScroll
	
	
	// Send click event to google
	function trackClick(obj) {
		pageTracker._trackPageview(obj.attr('href'));
	}//end trackClick
	
	
	// Function to move into site after intro
	function enterSite() {
		$('#siteContainer, div.content').fadeIn(2500, function() {
			$('body').removeClass('bodySuper');
			// Make sure scrolling works
			applyScroll($('div.productScroll'));
		});
		$('#supersize, #lgLogo').fadeOut(2500, function() {
			$('#supersize').remove();
		});
	}//end enter site
	
	
	// Function to check which slide we are on
	function checkSlide() {
		if ($('#supersize').children('.activeslide').hasClass('last')) {
			// Hide all others
			$('#supersize').children('a').not('.last').remove();
			clearInterval(slide_interval);
			// Hide supersize when the time is right
			setTimeout (enterSite, 3000);
		}//end if
		
	}//end clickSlide
	
	
	// Calls ajax to load up content
	function callAjax(obj, url, layout, method) {
		$.ajax({
			type: 'GET',
			url: url + '?SQ_DESIGN_NAME=clean&SQ_PAINT_LAYOUT_NAME='+layout,
			cache: true,
			beforeSend: function() {
				$('#siteContainer').append('<img class="load" src="/__data/assets/image/0017/6137/ajax-loader.gif" />');
				in_ajax = true;
			},
			success: function(data) {
				if (method == 'direct') {
					checkForImages(data, obj, true);
					$('#siteContainer').fadeIn(2500);
				} else {
					checkForImages(data, obj);
				}//end else
				
			}//end success
			
		});//end ajax
		
	}//end callAjax
	
	
	// Function to check when images are loaded
	function checkForImages(data, obj, showSite) {
		var test_data = $('<div />').html(data);
		var pageCount = $(test_data).find('div.productPages a').length;
		var imgCount = $('img', data).length;
		var imgLoad = 0;
		// Do we have images?
		if (imgCount === 0) {
			var temp_img = '<img src="/__data/assets/image/0018/6273/spacer.gif" />';
			data = data + temp_img;
		}
		// Count our images
		$('img', data).load(function() {
			imgLoad++;
			if (imgLoad >= imgCount) {
				images_loaded = true;
			}
		});//end load
		check_images = setInterval(function() {
			if (images_loaded) {
				// Increment our index
				glob_index++;
				id++;
				
				if ($('#content'+id).length === 0) {
					// Only add if this page has not been loaded
					// Why does IE hate this line?
					var cont_id = 'content'+id;
					data = '<div id="'+cont_id+'" class="content">'+data+'</div>';
					$('#content').prepend(data);
				}
				if (pageCount == 0) {
					$('#content'+id+' .productPages').hide();
				}
				// Fade in new content
				$('#content'+id).css('z-index', glob_index);
				$('#content'+id).fadeIn(2000, function() {
					
					// Make sure to hide all other pages
					if (use_child) {
						$('div.content').not('#content'+id).hide();
					} else {
						$('div.content').not(this).hide();
					}//end else
					$('.load').remove();
					
					// Bind some clicks
					$('#aboutK').click(function() {
						$(this).addClass('selected');
						$('#aboutA').removeClass('selected');
						
						$('#about2').fadeOut();
						$('#about1').fadeIn();
						
						return false;
						
					});
					$('#aboutA').click(function() {
						$(this).addClass('selected');
						$('#aboutK').removeClass('selected');
						
						$('#about1').fadeOut();
						$('#about2').fadeIn();
						
						return false;
						
					});
					
					// Done with ajax
					in_ajax = false;
				});
				applyScroll($('#content'+id+' div.productScroll'));
				// Clear
				clearInterval(check_images);
				return false;
			}//end if
		}, 500);//end setInterval
		
	}//end checkForImages
	
	/**
	* Function that cleans the input leaving just the asset id
	*
	* @param string		item_id				The id of the asset we are getting locks for
	*
	* @access public
	*/
	function clean_id(item_id) {
		return item_id.replace(/[^0-9]/g, '');
	}// End clean_id	
	
	
	// ##### On Page Load #####
	if (typeof asset !== 'undefined') {
		// Let our supersize run, then remove
		if ($('#supersize').length > 0) {
			// Initialize supersize
			$.fn.supersized.options = {  
				startwidth: 1667,  
				startheight: 1000,
				vertical_center: 0,
				slideshow: 1,
				navigation: 0,
				transition: 1,
				pause_hover: 0,
				slide_counter: 0,
				slide_captions: 0,
				slide_interval: slide_time  
			};
			$('#supersize').supersized();
			
			// Check to see what slide we are on
			slide_interval = setInterval(checkSlide, 500);
			
			
		} else {
			// Make sure that if we are on the top level, we load up the first child
			var top_nav_len = $('div.item a').length;
			var top_nav_curr = 0;
			$('div.item a').each(function() {
				var item_id = clean_id($(this).attr('id'));
				var obj = $(this);
				top_nav_curr++;
				// Check if we match a top level
				if (item_id == asset.assetid) {
					use_child = true;
					if (asset.assetid == '5838') {
						var info_url = true;
					}
					var layout = 'clean';
					// Hijack content!
					var url;
					if (asset.assetid == '5842' || asset.assetid == '10299' || asset.assetid == '5935') {
						url = asset.url;
					} else {
						url = $(this).parent().next('ul.subItems').find('a:first').attr('href');
					}
					if (info_url) {
						url = $(this).parent().next('ul.subItems').find('a:eq(1)').attr('href');
						$(this).parent().next('ul.subItems').find('a:eq(1)').addClass('selected');
						layout = 'clean-alt';
					} else {
						$(this).parent().next('ul.subItems').find('a:first').addClass('selected');
					}//end else
					
					// Call ajax!
					callAjax(obj, url, layout, 'direct');
					
					return false;
					
				} else {
					if (top_nav_len == top_nav_curr && !use_child) {
						$('#siteContainer, div.content').fadeIn(2500);
					}
				}
			});//end each
		}//end else
		
		// If we are just loading the page, we need to set our main nav as selected
		$('#main'+asset.assetid).addClass('selected');
		// Set our subs, if we are on that page
		if (asset.parent !== 'null') {
			// Add our selected classes
			$('#main'+asset.parent).addClass('selected');
			$('#sub'+asset.assetid).addClass('selected');
			// This means that we are on a sub page
			$('#sub'+asset.assetid).parent().parent('ul.subItems').fadeIn(2500);
		} else {
			// We are on the first level, but should show our children
			$('#main'+asset.assetid).parent('.item').next('ul.subItems').fadeIn(2500);
		}//end else
		
	}//end if
	
	// Deep linking!
/*	$.address.change(function(event) {
		var selection = $('a[rel=address:' + event.value + ']');
		$.address.title($.address.title().split(' | ')[0] + ' | ' + selection.text());				  
	});
*/	
	// Hide some things when we don't need them
	if (asset.assetid == '5826') {
		$('div.productPages, div.productDetails').hide();
	}
	
	// Hide additional product pages if there are none
	if ($('div.productPages a').length === 0) {
		$('div.productPages, div.productDetails').hide();
	}
	
	// Should we add scrollers to our image?
	if ($('div.productScroll').length > 0 && asset.assetid != '5826') {
		applyScroll($('div.productScroll'));
	}//end if
	
	// Move right to the side if user clicks slides
	$('#supersize a').click(function() {
		clearInterval(slide_interval);
		enterSite();
		return false;
	});
	
	// ##### Events #####
	// Contact Form
	$('#form_email_5843_submit').live('click', function() {
		var form_data = $('#form_email_5843').serialize();
		var submit_data = $(this).attr('name')+'='+$(this).val();
		var data = form_data+'&'+submit_data;
		if ($('#q5843_q1').val() !== 'Name' && $('#q5843_q2').val() !== 'Email' && $('#q5843_q3').val() !== 'Inquiry') {
			$.ajax({
				type: 'POST',
				url: '/contact?',
				data: data,
				beforeSend: function() {
					$('#siteContainer').append('<img class="load" src="/__data/assets/image/0017/6137/ajax-loader.gif" />');
					in_ajax = true;
				},
				success: function(data) {
					in_ajax = false;
					var thanks = 'Thank you for contacting Karen Caldwell Design.';
					$('#form_email_5843_submit').parent().after('<p>'+thanks+'</p>');
					$('img.load').remove();
				}//end success
				
			});//end ajax
		} else {
			alert('Please fill out all fields on the contact form.');
		}
		
		// Prevent Default
		return false;
		
	});
	
	
	// Main Navigation
	$('div.item a').live('click', function() {
		// Don't load if we are already there			   
		if ($(this).hasClass('selected') || in_ajax) {
			return false;
		}
		
		var obj = $(this);
		var layout = 'clean';
		
		// Check what layout to use
		var check_layout_id = clean_id($(this).attr('id'));
		if (check_layout_id == '5838') {
			layout = 'clean-alt';
			var info_url = true;
		}
		
		// Track
		trackClick(obj);
		
		var url;
		/*
		// Select first item
		var url = $(this).parent().next('ul.subItems').find('a:first').attr('href');
		if (info_url) {
			url = $(this).parent().next('ul.subItems').find('a:eq(1)').attr('href');
			$(this).parent().next('ul.subItems').find('a:eq(1)').addClass('top-selected');
		} else {
			$(this).parent().next('ul.subItems').find('a:first').addClass('top-selected');
		}//end else
		*/
		
		if ($(this).attr('id') == $('div.item:last a').attr('id') || $(this).attr('id') == 'main10299' || $(this).attr('id') == 'main5935') {
			url = $(this).attr('href');
			// Call ajax!
			callAjax(obj, url, layout, 'direct');
		}
		
		
		// Manage our fading menus
		if (!$(this).hasClass('selected')) {
			$('div.mainItems ul.subItems').fadeOut('slow', function() {
				// Make sure to remove the selected color
				$('ul.subItems a').removeClass('selected');
			});
			$(this).parent('.item').next('ul.subItems').fadeIn('slow');
		}//end if
		
		// Remove other selected
		$('.item a').removeClass('selected');
		// Add a selected class
		$(this).addClass('selected');
		
		// Prevent Default
		return false;
	
	});//end click
	
	
	// Sub Navigation
	$('ul.subItems a').live('click', function() {
		// Don't load if we are already there			   
		if ($(this).hasClass('selected') || in_ajax) {
			return false;
		}
		
		var obj = $(this);
		var layout = 'clean';
		var url = $(this).attr('href');
		
		// Check what layout to use
		var check_layout_id = $(this).parent().parent().prev('div.item').children('a').attr('id');
		if (clean_id(check_layout_id) == '5838') {
			layout = 'clean-alt';
		}
		
		// Track
		trackClick(obj);
		
		// Call ajax!
		callAjax(obj, url, layout, 'direct');
		
		// Remove other selected
		$('ul.subItems a').removeClass('selected top-selected');
		// Add a selected class
		$(this).addClass('selected');
		
		// Prevent Default
		return false;

	});//end click
	
	
	// Product Pages
	$('div.productPages a').live('click', function() {
		// Don't load if we are already there			   
		if ($(this).hasClass('selected') || in_ajax) {
			return false;
		}
		var layout = 'clean';
		if (($(this).hasClass('alt') || $(this).parent('div.productPages').hasClass('alt')) && asset.assetid !== '5935' && clickedID !== '5935') {
			layout = 'clean-alt';
		}
		
		if ($('#content').length === 0) {
			
		}//end
		
		var obj = $(this);
		
		// Track
		trackClick(obj);
		
		// Clean up!
		var etc = '&SQ_DESIGN_NAME=clean&SQ_PAINT_LAYOUT_NAME='+layout;
		var url = $(this).attr('href').replace(/etc/gi, '');
		
		url = url+etc;
		
		// Call ajax!
		callAjax(obj, url, layout, 'direct');
		
		// Prevent Default
		return false;

	});//end click
	
	
	// ### Zoom Images ###
	// Get our large image path
	$('#content a.mediaLink').live('click', function(){ 				
		var rel = $(this).attr('rel');
		
		// Remove
		if ($('#zedbox').length > 0) $('#zedbox').remove();
		
		// Stop if no image
		if (rel == '' || rel == '#') return false;
		
		var loc = $(this).attr('href');						 
		$('body').prepend('<div id="zedbox-blanket"></div>');
		$('body').prepend('<div id="zedbox"><img src="'+rel+'" alt="Zoomed" /><div class="close">Close</div></div>');
		
		$('#zedbox-blanket, #zedbox div.close, #zedbox').click(function() {
			$('#zedbox-blanket').remove();								
			$('#zedbox').fadeOut('fast');								
		});
		return false;
	});
	
	
});//end ready
