$.fn.showLoad = function(x,y) {
  $("#loaderpic").css({ top:y, left:x }).show();
};

$(document).ready(function(){

/* text placeholder */
	$(document).find(".placeholder").each(function() {
		if (typeof this.onclick != 'function') {return;}
		var placeholder = this.onclick();
		this.onclick = null;
		$(this).focus(function() {if (this.value == placeholder) this.value = '';});
		$(this).blur(function() {if (!this.value) this.value = placeholder;});
	});

	if($('.acc_body').length) {
		$('.acc_body').hide();
		
// ACTION AFTER CLICK ON BUTTONS
		$('.opt_button').click(function(e) {
			e.preventDefault();
			
			var counter;
			var acc_header_act = $(this).parents('.acc_header');
			var acc_body_act = $(this).parents('.acc_header').next('.acc_body');
			
			if($(this).hasClass('arraw-down'))
			{
				acc_body_act.slideToggle('fast');
			}
			else
			{
				acc_body_act.find('input:checkbox').attr('checked', false);
				acc_body_act.find('.ez-checked').removeClass('ez-checked');
				acc_header_act.find('.arraw-down').removeClass('active');
				acc_header_act.next('.acc_body:visible').slideToggle('fast');

				if($(this).parents('.option_block').hasClass('age_block')) { // CHANGED CLASSES AND ADD/REMOVE HIDDEN INPUTS WITH NAME/VALUE FOR AGE BLOCK
					$(this).toggleClass('active');

					if($(this).hasClass('active')) {
						counter = $(".option_block ul li").index($(this).parent("li")) + 1; // calculate element index from among the 'ul li' elements
						$(this).parent().append('<input type="hidden" name="ages[' + counter + ']" value="' + counter + '" />'); // hidden input formation
					}
					else $(this).parent().find('input').remove(); // remove hidden input if not active field
				}
				else if($(this).parents('.option_block').hasClass('gender_block')) { // CHANGED CLASSES AND ADD/REMOVE HIDDEN INPUTS WITH NAME/VALUE FOR GENDER BLOCK
					$(this).toggleClass('active');

					if($(this).hasClass('active')) {
						counter = $("div.block-50 div").index($(this).parent().parent()) + 1; // calculate element index from among the 'div' elements
						$(this).parent().append('<input type="hidden" name="genders[' + counter + ']" value="' + counter + '" />'); // hidden input formation
					}
					else $(this).parent().find('input').remove(); // remove hidden input if not active field
				}
				else $(this).addClass('active'); // CHANGED CLASSES FOR OTHER BLOCKS
			}
			
		}); // $('.opt_button').click(function(e)

// ACTION AFTER CLICK ON CHECKBOXES
		$('.acc_body').click(function(e) {
			var checked = false;
			$(this).find('input:checkbox').each(function() {
				if($(this).is(':checked')) checked = true;
				if(checked) {
					$(this).parents('.acc_body').prev('.acc_header').find('.opt_button').each(function() {
						if($(this).hasClass('arraw-down')) $(this).addClass('active');
						else $(this).removeClass('active');
						});
					}
				else {
					$(this).parents('.acc_body').prev('.acc_header').find('.opt_button').each(function() {
						if($(this).hasClass('arraw-down')) $(this).removeClass('active');
						else $(this).addClass('active');
						});
					}
				});
		}); // $('.acc_body').click(function(e)

// SELECT / UNSELECT ALL CHILD CHECKBOXES
		$('input[type="checkbox"]').click(function() {
			var checked = $(this).attr('checked');
			$(this).parent().parent().find('ul li').find('.ez-checkbox').each(function() {
				if(checked) $(this).addClass('ez-checked');
				else $(this).removeClass('ez-checked');

				$(this).find('input:checkbox').attr('checked', checked);
				});
			});

	$('input[type="checkbox"]').ezMark();
	}
	
	if($('a.fancy').length) {
		$('a.fancy').fancybox({
			ajax: {
				type: 'GET',
				data: 'isNaked=1&isAjax=1'
			},
			overlayColor: '#2786DF',
			overlayOpacity: .5, 
			autoScale: false,
			padding: 20,
			onComplete: function() {
				
				$(".isAjaxForm").live("submit", function() { //alert($(this).attr('action'));
				
					$.fancybox.showActivity();
					var isClose;
				
					$.ajax({
						type	: "POST",
						cache	: false,
						url		: $(this).attr('action'),
						data	: $(this).serializeArray(),
						success: function(data) {
							$.fancybox({
								onStart: function() {
												var associated = jQuery(data).find("input.associated").attr('value');
												if(associated) $(jQuery(data).find("input.associated").attr('name')).html(associated);
											},
								onComplete: function() {
												if($('.fancy_content').hasClass('reload_at_close')) isClose = true;
												else isClose = false;
											},
								content: data,
								padding: 20,
								onClosed: function() {if(isClose) parent.location.reload(true);} //reload page if .fancy_content selector has .'reload_at_close class
							});
						}
					});
				
					return false;
				});								
			}
		});
		
		$('a.fancy').each(function() {
				var replacedText = $(this).attr('rev');
				if(replacedText) {
					var curText = $(this).text();
					$(this).mouseenter(function() {$(this).addClass('hover').text(replacedText)})
							.mouseleave(function() {$(this).removeClass('hover').text(curText)});
				}
			});
	}

	if($('a.fancy_product').length) {
		var picID = 1; //alert('1 '+picID);
		$('a.fancy_product').click(function(e) {
			e.preventDefault();
			$.fancybox({
				href: this.href+'?isNaked=1&isAjax=1&pic='+picID,
				overlayColor: '#2786DF',
				overlayOpacity: .5,
				autoScale: false,
				padding: 20
			});
		});
		
		$('.thumb_images a').live('click', function(e) {
			e.preventDefault();
			var src = $(this).attr('href');
			$('.main_image').find('img').attr('src', src).removeAttr('width').removeAttr('height');
			$.fancybox.center;
		});
		
		$('#pthumbs li a').live('click', function(e) {
			e.preventDefault();
			var src = $(this).attr('rel'); //alert(src);
			$('#proddisp #loadarea .fancy_product').find('img').attr('src', src);
			picID = $(this).parent().index()+1; //alert('2 '+picID);
		});
	}
	
	if($('a.fancy_plain').length) {
		$('a.fancy_plain').fancybox({
				overlayColor: '#2786DF',
				overlayOpacity: .5,
				autoScale: false,
				padding: 20
			});
	}
	
	if($('.fancy_form').length) {
		$(".fancy_form").bind("submit", function() {
			$.fancybox.showActivity();
			$.ajax({
				type 	    : "POST",
				cache       : false,
				url         : "/Subscribe/?isNaked=1&isAjax=1&posting=1",
				data        : $(this).serializeArray(),
				success: function(data) {
							$.fancybox({
										content: data,
										padding: 20,
										onComplete: function() {
											$(".isAjaxForm").live("submit", function() {
												
											$.fancybox.showActivity();
											$.ajax({
												type	: "POST",
												cache	: false,
												url		: $(this).attr('action'),
												data	: $(this).serializeArray(),
												success: function(data) {
													$.fancybox({
														content: data,
														padding: 20
													});
												}
											});
											return false;
											});
										}
							});
						}
			});
			return false;
		});
	}

// CheckOut - Shipping-Address - QUICK SET VALUE FROM ONE OF 'My Address Book' BOX (EXCEPT COUNTRY)
	if($('a.ship_filling').length) {
		$('a.ship_filling').click(function(e) {
			e.preventDefault();
			var selector = $(this).parents('.info_box');
			
			var ship_name = selector.find('.ship_name').html();
			var ship_sddress1 = selector.find('.ship_address1').html();
			var ship_sddress2 = selector.find('.ship_address2').html();
			var ship_locality = selector.find('.ship_locality').html();
			var ship_state = selector.find('.ship_state').html();
			var ship_zip = selector.find('.ship_zip').html();
			var ship_country = selector.find('.ship_country').html();
			var ship_country_number = selector.find('input[name$="ShippingCountryNumber"]').val();
			var ship_phone = selector.find('.ship_phone').html();
			
			if(!ship_name) ship_sddrees2 = '';
			if(!ship_sddress1) ship_sddress2 = '';
			if(!ship_sddress2) ship_sddress2 = '';
			if(!ship_locality) ship_locality = '';
			if(!ship_state) ship_state = '';
			if(!ship_zip) ship_zip = '';
			if(!ship_country) ship_country = '';
			if(!ship_phone) ship_phone = '';
			
			$('#ShippingName').val(ship_name);
			$('#ShippingAddress1').val(ship_sddress1);
			$('#ShippingAddress2').val(ship_sddress2);
			$('#ShippingLocality').val(ship_locality);
			$('#ShippingState').val(ship_state);
			$('#ShippingZip').val(ship_zip);
			$('#ShippingPhone1').val(ship_phone);
			if($('select#ShippingCountry').length) {
				$("select#ShippingCountry :selected").removeAttr("selected");
				$('select#ShippingCountry').val(ship_country_number);
			}
//			else { reload page with GET param
//				window.location.replace(window.location.href + "?otherCountry=1&countryID=" + ship_country_number);
//			}
//	???		$('#ShippingCountry').val(ship_country);
		});
	}

//====== OPEN VERISIGN
	$('a.open_by_script').click(function(e) {	
		e.preventDefault(); 
		var win = 'width=520,height=470,left=200,top=200,menubar=no,location=no,titlebar=no,resizable=yes,scrollbars=yes';
		newWin = window.open(this.href,'VeriSign',win);
		newWin.focus();		
	});

//====== MAIN MENU
	$('#dropList ul.menu a.level1-a').mouseenter(function() {
													$(this).addClass('hover');
													$(this).parent().find('.listHolder').css('display', 'none').delay(400).fadeIn(200);
													})
									.mouseleave(function() {$(this).removeClass('hover')})
	$('#dropList ul.menu li').find('.listHolder').mouseenter(function() {$(this).parent().find('a.level1-a').addClass('hover')})
												.mouseleave(function() {$(this).parent().find('a.level1-a').removeClass('hover')})

//====== DELIVERY TAB IN DETAIL PRODUCT PAGE - CALCULATION
//load ajax indicator image
	$("<div id='loaderpic' style='position:absolute; top:-200px; left:-200px; z-index:2000'><img class='loaderpic' src='/images/ajax-loader.gif'></div>").appendTo("body");
	$("#loaderpic").ajaxStop(function(){ //hide ajax indicator after all ajax-queries
		$("#loaderpic").hide();
	});

	$('#delivery_text').find('.submit').live('click', function(e) {

var loadX = $(this).offset().left + 200;
var loadY = $(this).offset().top;
$(this).showLoad(loadX,loadY);
		
			e.preventDefault();
			var param = "isNaked=1&product=" + $("input[name='product']").val();
			if($('input#CalcZIP').length) param += "&CalcZIP=" + $('input#CalcZIP').val();
			$.ajax({
				type: "POST",
				url: '/Products/Delivery-Calculation-Product/',
				data: param,
				success: function(data){
					$('#delivery_text').replaceWith(data);
				}
			});
	});
	
// DESPATCH CENTRE
	$("input[name^=OrderCheckbox]").live('click', function() {
		if($('input[name^=OrderCheckbox]:checked').length) $('input.isDisable').removeAttr('disabled');
		else $('input.isDisable').attr('disabled', 'disabled');
		});
		
	if($("table.admintable1").length) {
		$("table.admintable1").find('td').mouseover(function() {$(this).parent("tr").addClass("hover")})
										.mouseout(function() {$(this).parent("tr").removeClass("hover")});
	}

	$('.strict').click(function(e) {
		var answer = confirm("Are you sure you wish to despatch ?");
		return answer;
		});
	$('.strict_delete').click(function(e) {
		var answer = confirm("Are you sure you wish to DELETE FOREVER ?");
		return answer;
		});

	/* TITLE SLIDER This code is executed after the DOM has been completely loaded */
	if($('#slides').length) {
		var blockHeight=0;
		var positions = new Array();
		
		$('#slides .slide').each(function(i){
			/* Traverse through all the slides and store their accumulative widths in totWidth */
			positions[i]= blockHeight;
			blockHeight += $(this).height();
			
			/* The positions array contains each slide's commulutative offset from the left part of the container */
			if(!$(this).height())
			{
				alert("Please, fill in width & height for all your images!");
				return false;
			}
			var classID = null;
			var classes = $(this).attr('class').split( ' ' );
			for (i = 0; i < classes.length; i++) {
				var classTmp = classes[i];
				if (classTmp.match( /^b/ )) {
					classID = classTmp;
					break;
				}
			}
			var bannerText = $(this).find('img').attr('alt');
			$("#menu").find("." + classID).find("a").each(function() {
					$(this).text(bannerText);
					$(this).css('padding-top', (64 - $(this).height())/2 + 'px');
				});
		});
		$('#slides').height(blockHeight);
	
		/* Change the cotainer div's width to the exact width of all the slides combined */
		$('#menu ul li a').click(function(e){
				/* On a thumbnail click */
				$('li.menuItem').removeClass('act').removeClass('afterActive').addClass('inact');
				$(this).parent().addClass('act');
				$(this).parent().next('li').addClass('afterActive');
				var pos = $(this).parent().prevAll('.menuItem').length;
				$('#slides').stop().animate({marginTop:-positions[pos]+'px'},450); /* Start the sliding animation */
				e.preventDefault(); /* Prevent the default action of the link */
		});
		
		$('#menu ul li.menuItem:first').addClass('act').siblings().addClass('inact'); /* On page load, mark the first thumbnail as active */
		
		/*****Auto-advance customization, added after the tutorial was released****/
		var current=1;
		function autoAdvance()
		{
			if(current==-1) return false;
			$('#menu ul li a').eq(current%$('#menu ul li a').length).click();
			current++;
		}
	
		// The number of seconds that the slider will auto-advance in:
		var changeEvery = 5;
		var itvl = setInterval(function(){autoAdvance()},changeEvery*1000);
		/* End of customizations */
		
		$(".slide img").hide(); //hide all the images on the page
	}
});

var i = 0;//initialize
var int=0;//Internet Explorer Fix
$(window).bind("load", function() {//The load event will only fire if the entire page or document is fully loaded
	var int = setInterval("doThis(i)",500);//500 is the fade in speed in milliseconds
});

function doThis() {
	var images = $(".slide img").length;//count the number of images on the page
	if (i >= images) {// Loop the images
		clearInterval(int);//When it reaches the last image the loop ends
	}
	$(".slide img:hidden").eq(0).fadeIn(500);//fades in the hidden images one by one
	i++;//add 1 to the count
}

$(window).resize(setWidth);
       $(document).ready(setWidth);
       function setWidth() {
         var de = document.documentElement;
         if((window.innerWidth || (de && de.clientWidth) || document.body.clientWidth) < 1158)
		 {
	         $(".popular_block td.image").hide();
			 $("ul.prod_list li").css("width","25%");
		 }
		 else
		 {
	         $(".popular_block td.image").show();
			 $("ul.prod_list li").css("width","20%");
		 }
}
