if ('undefined' === typeof window.console) {
	window.console = {
		log: function () {
			void(0);
		}
	};
}

function sendEmail(targetButton) {
	var elementsRoot = $(targetButton).parent().parent();
	var sendData = {
		emailSender : $(".emailSender", elementsRoot).val(),
		emailFrom : $(".emailFrom", elementsRoot).val(),
		emailTo : $(".emailTo", elementsRoot).val(),
		emailSubject : $(".emailSubject", elementsRoot).val(),
		emailBody : $(".emailBody", elementsRoot).val()
	};
	if (
		typeof(sendData) !== 'undefined'
     && typeof(sendData.emailSender) === 'string'
	 && typeof(sendData.emailFrom) === 'string'
	 && typeof(sendData.emailTo) === 'string'
	 && typeof(sendData.emailSubject) === 'string'
	 && typeof(sendData.emailBody) === 'string'
	) {
		elementsRoot.fadeOut(200, function() {
			$(".pleaseWait", elementsRoot.parent()).fadeIn(200, function() {
				$.post(
					'/email-ajax.php',
					sendData,
					function (receiveData) {
						$(".pleaseWait", elementsRoot.parent()).fadeOut(200, function() {
							if (1 === receiveData.status) {
								$(".emailSuccess", elementsRoot.parent()).fadeIn(200);
							}
							else {
								$(".emailError", elementsRoot.parent()).fadeIn(200);
							}
						});
					},
					'json'
				);
			});
		});
	}
}

function clearSpecifications()
{
	var postdata = { prod_id: $('#prod_id').val() };
	
	postdata = $.extend(postdata, { action: 'reset' });
	
	$.get(
		'/ajax_product.php',
		postdata,
		function (data) {
			var items_el = $('#items_block');
			items_el
				.html(data)
				.find('select')
				.change(function (e) {
					$(this).after('&nbsp;Зареждане...');
					updateItems(this);
				});
			$('#clear_specifications').bind('click', function(this_e){
				this_e.preventDefault();
				clearSpecifications();
			});
		},
		'html'
	);
}
function updateItems(that)
{
	var items_el = $('#items_block');
	
	if (items_el.length > 0) {
		var postdata = { prod_id: $('#prod_id').val() };
		
		if (null !== that) {
			postdata = $.extend(postdata, { name: $(that).attr('title'), value: $(that).val() });
		}
		
		$.get(
			'/ajax_product.php',
			postdata,
			function (data) {
				items_el
					.html(data)
					.find('select')
					.change(function (e) {
						$(this).after('&nbsp;Зареждане...');
						updateItems(this);
					});
				$('#clear_specifications').bind('click', function(this_e){
					this_e.preventDefault();
					clearSpecifications();
				});
				$('#productAdd').bind('click', function(this_e){
					this_e.preventDefault();
					$('#productForm').submit();
				});
			},
			'html'
		);
	}
}


function rateAjax(moduleName, record_id, name, value)
{
	jQuery.post(
		"/ajax_rate.php"
		,{
			action: "rate"
			,module: moduleName
			,rate_id: record_id
			,rate_name: name
			,rate_value: value
		}
		,function(responseText, textStatus, XMLHttpRequest)
		{
			// Callback function!!!   	//alert("done");
			//console.log(responseText);      //alert(textStatus); // success
			jQuery(responseText).each(function(key, serverData) {
				if(serverData.result==1) {
					if(serverData.position=="alert") {
						//alert(serverData.data);
						// replace this alert()
						
						if( $("#basicModalContent").length > 0 ) {
						
						}
						else {
							$("body").append('<div id="basicModalContent"></div>');
						}
						$('#basicModalContent').text( serverData.data ).modal();
					}
					if(serverData.position=="results_body") {
						jQuery('#selector').stop().fadeOut(200, function(){
							jQuery(this).html(serverData.data).fadeIn(200, function(){
								//jQuery('.selector').html(serverData.data);
							});
						});
					}
				}
			});
		}
		,"json"
	);
}


jQuery(function ($) {
	
	$('img').noContext(); // This caches all images, but not Highslide effect!
	
	
	
	var currContentHeight = 0;
	var maxContentHeight = 0;
	var currTitleHeight = 0;
	var maxTitleHeight = 0;
	var oneRowLevel = $(".oneRowLeveler");
	oneRowLevel.each(function() {
		var titleLeveler = $(this).find(".titleLeveler");
		titleLeveler.each(function() {
			currTitleHeight = $(this).height();
			//console.log(this, 'title height:', currTitleHeight, 'px');
			if (currTitleHeight > maxTitleHeight) {
				maxTitleHeight = currTitleHeight;
			}
		});
		titleLeveler.height(maxTitleHeight);
		//console.log('Setting all above objects\' title height to:', maxTitleHeight, 'px');
		currTitleHeight = 0;
		maxTitleHeight = 0;
		
		var contentLeveler = $(this).find(".contentLeveler");
		contentLeveler.each(function() {
			currContentHeight = $(this).height();
			//console.log(this, 'content height:', currContentHeight, 'px');
			if (currContentHeight > maxContentHeight) {
				maxContentHeight = currContentHeight;
			}
		});
		contentLeveler.height(maxContentHeight);
		//console.log('Setting all above objects\' content height to:', maxContentHeight, 'px');
		currContentHeight = 0;
		maxContentHeight = 0;
	});
	
	hs.graphicsDir = '/js/highslide/graphics/';
	hs.align = 'center';
	hs.transitions = ['expand', 'crossfade'];
	hs.outlineType = 'rounded-white';
	hs.fadeInOut = true;
	//hs.dimmingOpacity = 0.75;
	hs.blockRightClick = true;
	
	// Add the controlbar
	if (hs.addSlideshow) hs.addSlideshow({
		//slideshowGroup: 'group1',
		interval: 3000,
		repeat: false,
		useControls: true,
		fixedControls: false,
		overlayOptions: {
			opacity: 1,
			position: 'top right',
			hideOnMouseOut: false
		}
	});
	
	initFileUploads();
	
	$("#pass2").focus(function() {
		$("#pass2").hide();
		$("#logintop_pass").show().focus();
	});
	$("#logintop_pass").blur(function() {
    	if ($(this).val() == "") {
    		$("#pass2").show();
    		$("#logintop_pass").hide();
    	}
	});
	
	$("#gallery").jcarousel({
        scroll: 3,
        animation: 800
    });
    $("#jCarouselMenu").jcarousel({
        scroll: 10,
        animation: 800
    });
    $("#gallery1").jcarousel({
        scroll: 4,
        animation: 800
    });
	
	
	$("input:text").hint();
	
	var oneCatHeader = $("#allProdCatGall .oneCat h2, #allProdCatGall .oneCat .brandLinkTitle");
	oneCatHeader.each(function () {
		var currHeight = $(this).height();
		//console.log(currHeight);
		if ((currHeight > 25) && (currHeight < 40)) {
			$(this).addClass("twoRows");
		}
		if (currHeight >= 40) {
			$(this).addClass("threeRows");
		}
	});
	
	$("#lPanel .promotions .priceContainer .currPrice").dropShadow({
		left    : 1,
		top     : 3,
		blur    : 0,
		opacity : 1,
		color   : "#191919",
		swap    : false
	});
	
	$(".showFilter").click(function() {
		$("#filter").slideDown(500);
		$(this).fadeOut(500);
		return false;
	});
	$(".closeFilter").click(function() {
		$("#filter").slideUp(500);
		$(".showFilter").fadeIn(500);
		return false;
	});
	$(".showAllFilters").click(function() {
		thisHiddenDiv = $(this).parents(".oneSection").find(".hiddenFilters");
		if (thisHiddenDiv.is(":hidden")) {
			thisHiddenDiv.slideDown(500);
			$(this).text("по-малко...");
		} else {
			thisHiddenDiv.slideUp(500);
			$(this).text("повече...");
		}
		return false;
	});
	
	
	$(".inputButton, .inputButton2, #prodMenu h4, #filteredProducts h4, #rPanelFilters h4, .jcarousel-skin-menu .jcarousel-clip-horizontal").corner("3px"); // IE7 error unexpected call ... - do not make this to input type=submit!
	$("#prodMenu ul li a, #filteredProducts ul li").corner("5px");
	
	
	$('.noAction')
		.css('cursor', 'default')
		.click(function (e) {
			e.preventDefault();
		});
	$('.target_blank')
		.attr('target', '_blank');
		
	$('a.submitForm')
		.click(function (e) {
			e.preventDefault();
			$(this)
				.parents('form')
				.get(0)
				.submit();
		});

	$('#productAdd')
		.click(function (e) {
			e.preventDefault();
			$('#productForm')
				.submit();
		});
	
	
	updateItems(null);
	/*
	var items_el = $('#items_block');
	if (items_el.length > 0) {
		(updateItems = function (that) {
			var postdata = { prod_id: $('#prod_id').val() };
			
			if (null !== that) {
				postdata = $.extend(postdata, { name: $(that).attr('title'), value: $(that).val() });
			}
						
			$.get(
				'/ajax_product.php',
				postdata,
				function (data) {
					items_el
						.html(data)
						.find('select')
						.change(function (e) {
							updateItems(this);
						});
				},
				'html'
			);
		})(null);
	}
	*/
	/*
	var items_el = $('#items_block');
	if (items_el.length > 0) {
		(updateItems = function (that) {
			var postdata = { prod_id: $('#prod_id').val() };
			
			if (null !== that) {
				postdata = $.extend(postdata, { name: $(that).attr('title'), value: $(that).val() });
			}
			else {
				postdata = $.extend(postdata, { action: 'reset' });
			}
						
			$.get(
				'/ajax_product.php',
				postdata,
				function (data) {
					items_el
						.html(data)
						.find('select')
						.change(function (e) {
							updateItems(this);
						});
						
						$('#clear_specifications').bind('click', function(this_e){
							this_e.preventDefault();
							updateItems();
						});
				},
				'html'
			);
		})(null);
	}
	*/
	
	
	$('div.error')
		.each(function () {
			if (0 === $(this).html().length) {
				$(this).remove();
			}
		});
		
	$('#confirmCode')
		.click(function () {
			var src = $(this).attr('src');
			var pos = src.lastIndexOf('?');
			
			if (-1 === pos) {
			    pos = src.length;
			}
			
			src = src.substring(0, pos);
			
			$(this)
				.attr('src', src + '?' + Math.round(Math.random() * 9999999999));
		});
		
	$('#register_location')
		.change(function () {
			if ('-1' === $(this).val()) {
				$('#register_other_location:hidden')
					.slideDown(250, function () {
						$('#register_location')
							.removeAttr('name');
						$('#register_location_other')
							.attr('name', 'register_location')
							.focus()
							.select();
					});
			}
			else {
				$('#register_other_location:visible')
					.slideUp(250, function () {
						$('#register_location_other')
							.removeAttr('name');
						$('#register_location')
							.attr('name', 'register_location');
					});
			}
		});

	$('#addradd_location')
		.change(function () {
			if ('-1' === $(this).val()) {
				$('#addradd_other_location:hidden')
					.slideDown(250, function () {
						$('#addradd_location')
							.removeAttr('name');
						$('#addradd_location_other')
							.attr('name', 'addradd_location')
							.focus()
							.select();
					});
			}
			else {
				$('#addradd_other_location:visible')
					.slideUp(250, function () {
						$('#addradd_location_other')
							.removeAttr('name');
						$('#addradd_location')
							.attr('name', 'addradd_location');
					});
			}
		});

	$('#addredit_location')
		.change(function () {
			if ('-1' === $(this).val()) {
				$('#addredit_other_location:hidden')
					.slideDown(250, function () {
						$('#addredit_location')
							.removeAttr('name');
						$('#addredit_location_other')
							.attr('name', 'addredit_location')
							.focus()
							.select();
					});
			}
			else {
				$('#addredit_other_location:visible')
					.slideUp(250, function () {
						$('#addredit_location_other')
							.removeAttr('name');
						$('#addredit_location')
							.attr('name', 'addredit_location');
					});
			}
		});

	$('#invadd_company').click(function() {
		$('#name_field')
			.html('Име на фирмата: <span>*</span>');
		$('#in_field')
			.html('ЕИК: <span>*</span>');
		$('.error')
			.remove();
		$('.companyFields')
			.slideDown('fast');
	});
	
	$('#invadd_person').click(function() {
		$('#name_field')
			.html('Име: <span>*</span>');
		$('#in_field')
			.html('ЕГН: <span>*</span>');
		$('.error')
			.remove();
		$('.companyFields')
			.slideUp('fast');
	});

	$('#invedit_company').click(function() {
		$('#name_field')
			.html('Име на фирмата: <span>*</span>');
		$('#in_field')
			.html('ИН: <span>*</span>');
		$('.error')
			.remove();
		$('.companyFields')
			.slideDown('fast');
	});
	
	$('#invedit_person').click(function() {
		$('#name_field')
			.html('Име: <span>*</span>');
		$('#in_field')
			.html('ЕГН: <span>*</span>');
		$('.error')
			.remove();
		$('.companyFields')
			.slideUp('fast');
	});
	
	$('#order_location')
		.change(function () {
			if ('-1' === $(this).val()) {
				$('#order_other_location:hidden')
					.slideDown(250, function () {
						$('#order_location')
							.removeAttr('name');
						$('#order_location_other')
							.attr('name', 'order_location')
							.focus()
							.select();
					});
			}
			else {
				$('#order_other_location:visible')
					.slideUp(250, function () {
						$('#order_location_other')
							.removeAttr('name');
						$('#order_location')
							.attr('name', 'order_location');
					});
			}
		});

	$('#order_company').click(function() {
		$('#name_field')
			.html('Име на фирмата: <span>*</span>');
		$('#in_field')
			.html('ИН: <span>*</span>');
		$('.error')
			.remove();
		$('.companyFields')
			.slideDown('fast');
	});
	
	$('#order_person').click(function() {
		$('#name_field')
			.html('Име: <span>*</span>');
		$('#in_field')
			.html('ЕГН: <span>*</span>');
		$('.error')
			.remove();
		$('.companyFields')
			.slideUp('fast');
	});
	
	$('.sendRequest').click(function (e) {
	    $.nyroModalManual({
			content: $('#nyroRequestEmailForm').html(),
			modal: true
		});

		$.nyroModalSettings({ 
			width: 290,
			height: 270,
			endShowContent: function () {
				$('.requestEmailForm .emailSubject').val('Запитване за продукт');
				$('.requestEmailForm .emailBody').val('Здравейте,\r\n\r\nБих желал да получа повече информация относно следния продукт от електронния магазин на фирма Домко:\r\n\r\n' + location.href);
			}
		});
	});

	$('.sendFriend')
		.click(function (e) {
		    $.nyroModalManual({
				content: $('#nyroFriendEmailForm').html(),
				modal: true
			});
			
			$.nyroModalSettings({
				width: 290,
				height: 280,
				endShowContent: function () {
					$('.friendEmailForm .emailSubject').val('Интересен продукт от фирма Домко');
					$('.friendEmailForm .emailBody').val('Здравей,\r\n\r\nБих желал да ти покажа следния продукт от електронния магазин на фирма Домко:\r\n\r\n' + location.href);
				}
			});
		});
	
	$('#priceSelectors a')
		.click(function (e) {
			e.preventDefault();
			
			var rootEl = $('#priceSelectors');
			
			$('a', rootEl)
				.removeClass('selected');
				
			$(this)
				.addClass('selected');
			
			var prices = $(this).attr('href').substring(1);
			prices = prices.split('x')
			
			$('#input_price_from')
				.val(prices[0]);
			$('#input_price_to')
				.val(prices[1]);
		});
		
	$('a[href="' + '#' + $('#input_price_from').val() + 'x' + $('#input_price_to').val() + '"]')
		.addClass('selected');

	$('#lPanel .basket .productTable input:eq(0)')
		.focus();
		
	$('#clearAllFilters, #clearAllFilters2')
		.click(function (e) {
			e.preventDefault();
			
			location.href = '?delallfilters';
		});
	
	
	$('#icon_favourite').click(function(e){
		e.preventDefault();
		
		var pageName = "Домко";
		
		var urlAddress = $('#icon_favourite').attr('href');
		//var pageName = $('title').text(); //ie7 do not work
		
		if (window.sidebar) {
			// firefox
			//window.sidebar.addPanel(pageName, urlAddress, ""); //Dont use until it's fixed - Problem: The bookmark is saved, but it is opened in the sidebar, not main window! (ff3...)
			//alert('Натиснете CTRL+D за да запазите тази страница!');
			
			if( $("#basicModalContent").length > 0 ) {
			
			}
			else {
				$("body").append('<div id="basicModalContent"></div>');
			}
			$('#basicModalContent').text( 'Натиснете CTRL+D за да запазите тази страница!' ).modal();
		}
		else if (window.external) {
			window.external.AddFavorite(urlAddress,pageName);
		}
		
		return false;
	});
	
	$('.star_rating_1').rating({
		callback: function(value, link){
			var input_name = "star_rating_1";
			var this_form = $(this).parents().find('form');
			var this_form_id = this_form.attr('id');
			var record_id = $('#'+this_form_id+' input[name="rate_id"]').val();
			
			rateAjax('mod_1', record_id, input_name, value);
		}
		,required: true
	});
	
	// Call directly with specific selector and not into EACH() loop. It doesn't open correct index of the clicked link
	$("a#terms_link[rel^='prettyPhoto']").prettyPhoto({
		animationSpeed: 'normal', /* fast/slow/normal */
		padding: 40, /* padding for each side of the picture */
		opacity: 0.35, /* Value betwee 0 and 1 */
		showTitle: false, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'light_rounded_2', /* light_rounded / dark_rounded / light_square / dark_square */
		hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
		modal: false, /* If set to true, only the close button will close the window */
		changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
		callback: function(){} /* Called when prettyPhoto is closed */
	});
	
	
	$(".formQuantityChange").each(function(index, domEle) {
		// domEle == this
		$('.inputTextCount', domEle).bind('change', function() {
			$('a.buttonFinishOrder', domEle).unbind('click').addClass('buttonFinishOrderDisabled').bind('click', function(e) {
				e.preventDefault();
				alert('Моля, обновете количествата!');
			}).animate({'opacity': 0.4});
		});
	});
	
});


