$(document).ready(function () 
{
	//$("#registerform").validationEngine();
	imagePreview();
	preLoadImagesArray = new Array();
	headingTextArray = new Array();
	iconURLArray = new Array();
	headingArray = new Array();
	descriptionArray = new Array();
	
	
	headingText = $(this).find('heading_text').text(); 
	//horizontal javascript
	$("#mainnav_h > li").hover(
		
		function(e){
			$this = $(this)
			$this.addClass("hover");			
		},
		function(e){
			$this = $(this)
			$this.removeClass("hover");

		}	
	);
	
	
	//vertical navigation js
	$(".mainnav_v a").hover(
		function (e) 
		{
			$this = $(this)
			$this.stop().animate({	paddingLeft : '16px'}, 300, function(){peek("DesignerFrames"); peek("DesignerSunglasses");});
		},
		function (e)
		{
			$this = $(this);
			$this.stop().animate({	paddingLeft : '0px'	}, 300);
			$('#peek_container').remove();
		}
	);
	//product list grid or list style
	$('.product_grid').click(function(){
		$('.product_container_list').removeClass("product_container_list").addClass("product_container");
	});
	$('.product_list').click(function(){
		$('.product_container').removeClass("product_container").addClass("product_container_list");
	});
	
	$('.close_ico').click(function(){
		$(this).parent().parent().parent().hide();
	});
	$('.Sinput').css('opacity',0.5);
	
	//Ajax Search
	//this path should always be absolute
	$.ajax({type:"GET",url:"http://www.photodent.com/img/shop/photodent.com/contents/keywords/keywords.txt",dataType:"text",success:function(keys){var data=keys.split(" "); $("#autoSearch").autocomplete(data);}});


	//fancybox
	$("a.box").fancybox({
	'scrolling'		: 'no',
	'titleShow'		: false
	});	
	 
	
	//Fly to Basket Animation frame only
	$(".flyToBasket").click(function() {
		
		gotoX=600;
		gotoY=-350;
		newImageWidth=56;
		newImageHeight=53;
				
		$("#imgFly img")
		.clone()
		.prependTo("#imgFly")
		.css({'position' : 'absolute'})
		.animate({opacity: 0.4}, 100 )
		.animate({opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, 
				 function()
				 {
					$(this).remove();
					document.forms.productform.submit();
				 }
		);
	});

	
	//slideshow
	/*$('#slideshow').SexySlider({
		width  		: 960,
		height 		: 250,
		delay		: 3000,
		strips		: 1,
		autopause	: true,
		auto		: true, 
		//autopause	: true, 
		delay		: 3000, 
		stripSpeed	: 500,  
		titleOpacity: 0.7,  
		titleSpeed	: 1000, 
		direction	: 'right', // left, right, alternate, random
		effect		: 'curtain', // curtain, zipper, wave, fountain, cascade, random
		navigation	: '#slideshow-nav'
        //control		: '#slideshow-control'
    });
	$('#sub_slideshow').SexySlider({
		width  		: 760,
		height 		: 100,
		delay		: 3000,
		strips		: 1,
		autopause	: true,
		auto		: true, 
		//autopause	: true, 
		delay		: 3000, 
		stripSpeed	: 500,  
		titleOpacity: 0.7,  
		titleSpeed	: 1000, 
		direction	: 'right', // left, right, alternate, random
		effect		: 'curtain' // curtain, zipper, wave, fountain, cascade, random
		//navigation	: '#slideshow-nav',
        //control		: '#slideshow-control'
    });*/

	$("#slideshow").xmlSlider(
		{	'xmlFile':"http://www.photodent.com/img/shop/photodent.com/contents/slideshow/xml/slideshow.xml",
			'toggleBtn':true,
			'navBtn':true,
			'easing':new Array("easeInSine","easeOutSine"),
			'backward':"<img src='http://www.photodent.com/img/shop/photodent.com/contents/slideshow/imgs/previous.png' alt='Previous'/>",
			'forward':"<img src='http://www.photodent.com/img/shop/photodent.com/contents/slideshow/imgs/next.png' alt='Next'/>",
			'pagination':"",
			'width': 960.0,
			'height': 250.0,
			'speed':1000,
			'timeout':5000
	  	}
	);
	cards();

	$(window).load(function(){
		$('.product_img_column').each(function(){
			var maxWidth = 150; // Max width for the image
			var maxHeight = 150;       // Max height for the image
			$(this).children("a").children("img.catimg").css("width", "auto").css("height", "auto"); // Remove existing CSS
			$(this).children("a").children("img.catimg").removeAttr("width").removeAttr("height"); // Remove HTML attributes
			var width = $(this).children("a").children("img.catimg").width();    // Current image width
			var height = $(this).children("a").children("img.catimg").height();  // Current image height
	
			if(width > height) {
					// Check if the current width is larger than the max
					if(width > maxWidth){
							var ratio = maxWidth / width;   // get ratio for scaling image
							$(this).children("a").children("img.catimg").css("width", maxWidth); // Set new width
							$(this).children("a").children("img.catimg").css("height", height * ratio);  // Scale height based on ratio
							height = height * ratio;        // Reset height to match scaled image
					}
			} else {
					// Check if current height is larger than max
					if(height > maxHeight){
							var ratio = maxHeight / height; // get ratio for scaling image
							$(this).children("a").children("img.catimg").css("height", maxHeight);   // Set new height
							$(this).children("a").children("img.catimg").css("width", width * ratio);    // Scale width based on ratio
							width = width * ratio;  // Reset width to match scaled image
					}
			}
		});
	});

	
	//$(".product_item_small").kepresize({maxWidth: 450,maxHeight:'auto'});
	 
});//end dom
/*****************************************resize product images on product item page*******************************************************************/
$.fn.kepresize = function(options){

		var defaults = {  
			maxWidth : 110,  // Max width for the image
			maxHeight : 115  // Max height for the image
		};

		var options = $.extend(defaults, options); 

		return this.each(function() {
			obj = $(this);
			
			// Nulling widht and height
			var width = 0;
			var height = 0;
			
			// Get image parameters, and calculate scale
			var width = obj.width();    // Current image width
			var height = obj.height();  // Current image height
			var x_scale = width / options.maxWidth;   // X scale
			var y_scale = height / options.maxHeight; // Y scale
			
			if(y_scale > x_scale){
				new_height = Math.ceil(height * (1/y_scale));
				new_width = Math.ceil(width * (1/y_scale));
				obj.css("height", new_height);
				obj.css("width", new_width);
			} else {
				new_height = Math.ceil(height * (1/x_scale));
				new_width = Math.ceil(width * (1/x_scale));
				obj.css("height", new_height);
				obj.css("width", new_width);
			}
		});
		
	};

/*****************************************check terms and condition*******************************************************************/
function checkTermsAgreement() {
	
	var button = document.getElementById('submit');
	var terms_checkbox = document.getElementById('terms');

	var all_ok = true;

	if (!terms_checkbox.checked) { 
		all_ok = false; 
	}

	
	if (all_ok == true) {
		return true;
	} else {
		alert('You must agree fully to the terms and conditions of sale before you can proceed.');
		return false;
	}
}
/*****************************************visa cards hover *******************************************************************/
function cards(){

	$("div.card_hover").each(
		function(){
			
			var imgName=$(this).attr("title");
			var imgwidth=$(this).attr("id");
			this.title="";
			$(this).css({'background' : 'url('+imgName+') 0px 0px no-repeat', 'width' : ''+imgwidth+'px', 'height' : '32px','padding':'0 10px 0 0'});
			
			$(this).hover(
				function(){
					$(this).css({'background' : 'url('+imgName+') 0px 32px repeat-y'});
				},
				function(){
					$(this).css({'background' : 'url('+imgName+') 0px 0px repeat-y'});
				}
			);
		}
	);
}
/*******************************************************Utillity Functions****************************************/
$.clientCoords = function() { //this returns screen dimensions
     var dimensions = {width: 0, height: 0};
     if (document.documentElement) {
         dimensions.width = document.documentElement.offsetWidth;
         dimensions.height = document.documentElement.offsetHeight;
     } else if (window.innerWidth && window.innerHeight) {
         dimensions.width = window.innerWidth;
         dimensions.height = window.innerHeight;
     }
     return dimensions;
}
$.fn.center = function () {//this makes the loading animation center
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}
$.fn.pause = function(duration) {// this gives a pause to any event
    $(this).animate({ dummy: 1 }, duration);
    return this;
};
/*******************************************************full screen basket****************************************/
function fullscreenbasket()
{
	$("#leftClose").css("opacity","0.8");
	$("#leftOpen").css("opacity","0.8");
	
	$("#leftside_wrapper").slideUp("slow", function(){$("#right").animate({width:'+=200px'},300); $("#leftOpen").show(); });
	
	//$("#right").animate({width:'+=190px'},300,function(){$("#left").slideUp("slow");});
	$("#leftside_wrapper").hover(
		function(){
			$("#leftClose").show();
		},
		function(){
			$("#leftClose").hide();
		}
	);
	
	$("#leftClose").click(function(){ $("#leftside_wrapper").slideUp("slow", function(){$("#right").animate({width:'+=200px'},300); $("#leftOpen").show(); });});
	$("#leftOpen").click(function(){ $("#right").animate({width:'-=200px'},300,function(){$("#leftside_wrapper").slideDown("slow");});  $("#leftOpen").hide(); });
}
/*************************************message after successfull addition of product in basket shopping basket ot continue shopping***************/
function message()
{
	//alert("product added");
	$(".loading_pres").css({"width":$.clientCoords().width,"height":$.clientCoords().height,"display":"block","opacity":"0.2"})//
	$(".addtoBasketSuccessMsg").css("display","block").center();
}
/*******************************************************checkout message****************************************/
function checkoutMsg()
{
	//alert("product added");
	$(".loading_pres").css({"width":$.clientCoords().width,"height":$.clientCoords().height,"display":"block","opacity":"0.2"})//
	$(".checkoutMsg").css("display","block").center();
}
/*******************************************************Product image Zoom****************************************/
$(function() {
	var options = {
		zoomWidth: 200,
		zoomHeight: 200,
		//xOffset: 10,
		//yOffset: 0,
		//position: "",
		lens:true
		//imageOpacity:,
		//title:true,
		//showEffect:,
		//hideEffect:,
		//fadeinSpeed:,
		//fadeoutSpeed:,
		//showPreload:true,
		//preloadText: "Loading Image"
		//preloadPosition:,
	};
	$(".jqzoom").jqzoom(options);
});
/*******************************************************Product image hover****************************************/
function imagePreview(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br>" + this.t : "";
		var newName = this.name;
		//console.log(this.name);
		//newName=newName.replace("/l/","/o/");
		//console.log(newName);
		$("body").append("<p id='preview'><img src='"+ this.name +"' alt='Image preview' style='margin-bottom:5px;'>"+ c +"</p>");
		$("#preview img").error(function () {
			$("#preview img").append("<span class='red'>&nbsp;&nbsp;Can not load image, please report this error</span>");
		});
		
		widthOfImage= $("#preview img").attr("width");
		if(widthOfImage>400){ $("#preview img").attr("src" ,newName).css({'width': '400px', 'height': 'auto'}); }
		
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("a.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};
/*******************************************************Slide Show****************************************/
function slideshow()
{
	var i = 0;
	var $this=$(this);
	$('.image_thumb').append('<ul></u>');
	$.ajax({
		type:"GET",
		url: "http://www.photodent.com/img/shop/photodent.com/contents/slideshow/slideshow.xml",//this path should always be absolute
		cache: true,
		//ie bug : it send wrong datatype on localmachine
		dataType: ($.browser.msie) ? "text" : "xml",
		success: function(data) 
		{
			var xml;
			if (typeof data == "string")
			{
				xml = new ActiveXObject("Microsoft.XMLDOM");
				xml.async = false;
				xml.loadXML(data);
			}
			else 
			{
				xml = data;
			}
		
			$("tab",xml).each(
				function()
				{
					
					var heading = $(this).find('heading').text();
					var headingText = $(this).find('heading_text').text();
					var cls = $(this).find('heading').attr('class');
					var iconURL = $(this).find('icon').text();
					var slideURL = $(this).find('image').text();
					var description = $(this).find('description').text();

					$('<li class="'+cls+'"></li>').html('<a href="'+slideURL+'"><img src="'+iconURL+'" alt="'+heading+'"></a><div class="block" id="'+i+'"><h2 class="smallh2">'+heading+'<br /><span>'+headingText+'</span></h2><p>'+description+'</p></div>').appendTo('.image_thumb ul');
					
					i += 1;
					
					//slideURL = "http://ukcatonline.com/test/"+slideURL;
					headingArray.push(heading);
					headingTextArray.push(headingText);
					iconURLArray.push(iconURL);
					preLoadImagesArray.push(slideURL);
					descriptionArray.push(description);
				}
			);//EOF each
			
			$('.main_image').append('<img id="mainimg" src="'+preLoadImagesArray[0]+'" alt="'+headingArray[0]+'"><div style="display: block;" class="desc"> <a href="#" class="collapse">Close Me!</a><div style="opacity: 0.8;" class="block"><h2>'+headingArray[0]+'<br />'+headingTextArray[0]+'</h2><p>'+descriptionArray[0]+'</p></div></div>');
			preLoadImages(preLoadImagesArray);
			$('.active').prepend('<div style="float:left;"><div class="highlight"></div></div>');
			
		},//EOF ajax success
		
		complete: function()
		{
			$(".main_image .desc").show();
			$(".main_image .block").animate({opacity : 0.8 }, 1 );
			$(".image_thumb ul li:first").addClass('active');
			$(".main_image .block").hide();
			
			$(".image_thumb ul li").click(function()
			{	
				var imgAlt = $(this).find('img').attr("alt");
				var imgTitle = $(this).find('a').attr("href");
				var imgDesc = $(this).find('.block').html();
				var imgDescHeight = $(".main_image").find('.block').height();
				//console.log($(this).find('div').attr('id'));
				if ($(this).is(".active"))
				{
					return false;
				}
				else 
				{
					$(".main_image .block").animate({opacity : 0, marginBottom : - imgDescHeight }, 250 , function(){
						$(".main_image .block").html(imgDesc).animate( {opacity : 0.85, marginBottom : "0" }, 250 ); 
						$(".main_image img").attr({ src: "images/indicator.gif" , alt: imgAlt});
						$(".main_image img").attr({ src: imgTitle , alt: imgAlt});
					});
																																																												
					
					
					/*$(".main_image .block").animate({opacity : 0, marginBottom : - imgDescHeight }, 150 , function(){
						$(".main_image .block").html(imgDesc).animate( {opacity : 0.85, marginBottom : "0" }, 150 ); 
						
						//fade transition
						$(".main_image img").animate({opacity:0},150,function(){
							$(".main_image img").animate({opacity:1},150); 
							$(".main_image img").attr({ src: imgTitle , alt: imgAlt}); 
						});
		
					});*/
				}
				
				$(".image_thumb ul li").removeClass('active');
				$('.highlight').remove();
				$(this).prepend('<div style="float:left;"><div class="highlight"></div></div>');
				$(this).addClass('active');
				return false;
				$active = $(this);//auto-rotate
				slideSwitchClick();//auto-rotate
				
			}).hover(function()
				{ 
					$(this).addClass('hover');
					
					clearInterval(playSlideshow);//auto-rotate 
					playSlideshow = setInterval(slideSwitchTimed, 4000 );//auto-rotate
				}
					,function(){ $(this).removeClass('hover'); } );
			
			$(function() { playSlideshow = setInterval(slideSwitchTimed, 4000 ); });//auto-rotate 
			
			$("a.collapse").click(function() { $(".main_image .block").slideToggle(); $("a.collapse").toggleClass("show"); });
			
			function slideSwitchTimed()
			{
				$active = $('.image_thumb ul li.active').next();
				if ( $active.length == 0 ) $active = $('.image_thumb ul li:first');
				slideSwitch();
			}
			
			function slideSwitchClick() 
			{
				slideSwitch();
			}
			
			function slideSwitch() 
			{
				var $prev = $('.image_thumb ul li.active');
				//Show active list-item
				$prev.removeClass('active');
				$('.highlight').remove();
				$active.prepend('<div style="float:left;"><div class="highlight"></div></div>');
				$active.addClass('active');
				
				//Set Variables
				var imgAlt = $active.find('img').attr("alt");
				var imgTitle = $active.find('a').attr("href");
				var imgDesc = $active.find('.block').html();
				var imgDescHeight = $(".main_image").find('.block').height();
				var ids = $active.find('.block').attr("id");
				//imgTitle = "http://ukcatonline.com/test/"+imgTitle;
				//headingArray,headingTextArray,iconURLArray,preLoadImagesArray,descriptionArray
				//console.log(descriptionArray[ids],preLoadImagesArray[ids],headingArray[ids]);
				//console.log(ids);
				if ($(this).is(".active")) {
					return false;
					} else {
					
					$(".main_image img").animate({ opacity: 0}, 250 );
				$(".main_image .block").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() {
						$(".main_image .block").html(imgDesc).animate({ opacity: 0.85, marginBottom: "0" }, 250 );
						$(".main_image img").attr({ src:  imgTitle, alt: imgAlt}).animate({ opacity: 1}, 250 );
						//$(".main_image img").remove('#mainimg');
						//$(".main_image img").prepend('<img style="opacity: 0;" src="'+imgTitle+'" alt="">');
					});
				}
				return false;
			}//EOF slideswitch()
		}//EOF complete
	});//EOF AJAX
					
}//EOF slideshow
/*******************************************************Peek****************************************/
function peek(categoryName){
		var brand ="";
		var category=categoryName;
		$this.each(function() 
		{
			var title = this.title;
			if ($this.is('a') && $this.attr('title') != '' && $this.attr('id')==category)
			{  
				brand= this.title;

				$.ajax({
					type: "GET",
					url: "http://www.photodent.com/img/shop/photodent.com/contents/peek_menu/peek_menu.xml",//this path should always be absolute
					//ie bug : it send wrong datatype on localmachine
					dataType: ($.browser.msie) ? "text" : "xml",
					success: function(data) 
						{
							var xml;
							if (typeof data == "string")
							{
								xml = new ActiveXObject("Microsoft.XMLDOM");
								xml.async = false;
								xml.loadXML(data);
							}
							else
							{
								xml = data;
							}
							
							//could have used $(xml).find(category).each(function() but jquery is intelligent enough to know wat element is currently selected
							$(category, xml).each(
								function()
								{
									$(brand,this).each(
										function()
										{
											var title = $(this).attr('title');
											var imgurl = $(this).attr('imgurl');
											var description = $(this).find('description').text();
											var feature1 = $(this).find('feature1').text();
											var feature2 = $(this).find('feature2').text();
											var feature3 = $(this).find('feature3').text();
											var feature4 = $(this).find('feature4').text();
										
											var html =  '<div id="peek_container"><img src="' + imgurl + '" alt="" /><br /><br /><h1>'+title+'</h1><br />';
											html += '<p>' + description + '</p><br />';
											html += '<ul><li>'+feature1+'</li><li>'+feature2+'</li><li>'+feature3+'</li><li>'+feature4+'</li></ul><br /></div>';
											
											$this.parent().append(html);
										}
									);
								}
							);
						}
				});
			}
		});
	}//peek function ends
/*******************************************************preload images****************************************/
function preLoadImages(imageArray)
	{
		var cache = [];
		var count = imageArray.length;
		for (var i = count; i--;) 
		{
			var cacheImage = document.createElement('img');
			cacheImage.src = imageArray[i];
			cache.push(cacheImage);
		}
	}

