﻿/// <reference path="jquery-1.3.2-vsdoc.js">
/// <reference path="modal.js">


function explode(delimiter, string) {

	var emptyArray = { 0: '' };

	if (arguments.length != 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined') {
		return null;
	}

	if (delimiter === ''
        || delimiter === false
        || delimiter === null) {
		return false;
	}

	if (typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object') {
		return emptyArray;
	}

	if (delimiter === true) {
		delimiter = '1';
	}

	return string.toString().split(delimiter.toString());
}

jQuery.fn.outerHTML = function(s) {
	return (s)
	? this.before(s).remove()
	: jQuery("<p>").append(this.eq(0).clone()).html();
}

jQuery.fn.center = function() {
	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;
}

jQuery.fn.exists = function() { return jQuery(this).length > 0; }

var clickEvent = function(e) {
	e.preventDefault();
	var button = $(this);
	$.unblockUI({
		onUnblock: function() {
			button.unbind('click', clickEvent);
			button.click();
		}
	});
}

$(function() {
	master_switch($(document).find(".label[rel='master_switch']"));
	$(document).find(".label[rel='master_switch'] select").change(function() {
		master_switch($(this).parents(".label"));
	});
	function master_switch(obj) {

		if (obj.attr("rel") == "master_switch") {

			var value = obj.find("select").val();
			if (value == "") {
				value = obj.find("select option:first").val();
			}

			$(document).find(".label[rel]").not("[rel='master_switch']").hide();
			$(document).find(".label[rel='" + value + "']").show();
		};
	};
	$.toggle();
});

function openWindow(url, height, width, scrollbars) {
	var top = (screen.height - height) / 2;
	var left = (screen.width - width) / 2;

	//if (window.showModalDialog) 
	//{
	//  window.showModalDialog(url, "_blank",
	//  "dialogWidth:"+width+"px;dialogHeight:"+height+"px;top:"+top+"px;left:"+left+"px;");
	//} 
	//else
	//{
	var prop = 'height=' + height +
            ',width=' + width +
            ',top=' + top +
            ',left=' + left +
            ',toolbar=no,directories=no,status=no,menubar=no' +
            ',scrollbars=' + (scrollbars || '1');
	var win = window.open(url, 'popup', prop);
	win.focus();
	//}
}

function onCalendarShown(sender, args) {
	sender._selectedDate = new Date(1980, 1, 1, 0, 0, 0, 0);
	sender._switchMode("years", true);
	//sender._switchMode("months", true);            
}

function showAddCart(productId) {
	var div = $('.modalBackground').fadeTo(1, 0, function() {
		div.css("display", "block");
		div.fadeTo("fast", 0.3);
	});

	$('#warrantyPopup' + productId).show();
}

function showRatingBox(productIdField, productId, productNameField, productName) {
	$('#' + productIdField).attr('value', productId);
	$('#' + productNameField).text(productName);

	var ratingBox = $('#prating');

	//$.blockUI.defaults.css = {};
	$.blockUI({
		message: ratingBox,
		css: {
			width: '300px',
			textAlign: 'center'
		}
	});

	$('.btnSaveRating').click(clickEvent);

	$('.blockOverlay').click($.unblockUI);
}

function hideRatingBox() {
	$.unblockUI();
	$('.blockOverlay').unbind('click', $.unblockUI);
}

function hideBonusBox() {
	$.unblockUI();
	$('.blockOverlay').unbind('click', $.unblockUI);
}

function showBonusBox(productId, productIdTo, quantityFrom, quantityTo, okBtn, okScript, command, commandTo) {
	$('#' + productIdTo).attr('value', productId);
	$('#' + commandTo).attr('value', command);
	var quantity = $('#' + quantityFrom).val();
	$('#' + quantityTo).attr('value', quantity);

	if (okScript != undefined) {
		$('#' + okBtn).click(okScript);
	} else {
		$('#bonusBox .btnAddToCart').click(clickEvent);
	}

	var bonusBox = $('#bonusBox');

	//$.blockUI.defaults.css = {};
	$.blockUI({
		message: bonusBox,
		css: {
			width: '450px',
			textAlign: 'left'
		}
	});


	$('.blockOverlay').click($.unblockUI);
}

function showGuaranteeBox(productId, fieldId, productName, price, guaranteePrice, nameField1, nameField2, priceField, guaranteeField, amountFrom, amountTo, leaseField, withLease) {
	$('#' + fieldId).attr('value', productId);
	var name = $('#' + productName).text();
	$('#' + nameField1).text(name);
	$('#' + nameField2).text(name);
	$('#' + priceField).text(price);
	$('#' + leaseField).attr('value', withLease);
	$('#' + guaranteeField).text(guaranteePrice);
	var amount = $('#' + amountFrom).val();
	$('#' + amountTo).attr('value', amount);

	var guaranteeBox = $('#guaranteeBox');

	//$.blockUI.defaults.css = {};
	$.blockUI({
		message: guaranteeBox,
		css: {
			width: '250px',
			textAlign: 'left'
		}
	});

	$('#guaranteeBox .btnAddToCart').click(clickEvent);

	$('.blockOverlay').click($.unblockUI);
}

function addToCart_item(productId) {
	if ($("#add_to_cart_id").length) {
		$("#add_to_cart_id").val(productId);
	} else {
		$("form").append("<input type=\"hidden\" id=\"add_to_cart_id\" name=\"add_to_cart_id\" value=\"" + productId + "\">")
	}
}


function hideGuaranteeBox() {
	$.unblockUI();
	$('.blockOverlay').unbind('click', $.unblockUI);
}

function hideAddCart(productId) {
	$('.modalBackground').hide();
	$("#warrantyPopup" + productId).hide();
}

function checkEnter(event, buttonIdToClick) {
	//	return;
	//	var keynum;
	//	
	//	if (window.event) // IE
	//	{
	//		keynum = event.keyCode;
	//	}
	//	else if (event.which) // Netscape/Firefox/Opera
	//	{
	//		keynum = event.which;
	//	}

	//	if (keynum == 13) {
	//		var btn = $(buttonToClick);
	//		btn.click();
	//		return false;
	//	}
	//	return true;
}

function BindEnterKeys() {
	$("input, select").each(
		function(intIndex) {
			if (!$(this).attr("onKeyPress")) {
				// CustomerForms have only 1 submit button... these can be used for the click event
				var closestSubmit = $(this).closest(".section.CustomerForm,.section.User").find("input[type = submit]");
				//var closestSubmit = GetClosest($(this), "input[type = submit]");
				if (closestSubmit && closestSubmit.attr("id")) {
					$(this).attr(
						"onKeyPress",
						"return OnEnter(event, function() { $('#" + closestSubmit.attr("id") + "').click(); })"
					);
				} else {
					$(this).attr(
						"onKeyPress",
						"return OnEnter(event, function() { void(0); })"
					);
				}
			}
		}
	);
}

function GetClosest(element, pattern) {
	var closestSection = $(element).closest(".section");
	while (element) {
		var submit = $(element).find(pattern);
		if (submit.length > 0)
			return submit;
		if ($(element).attr("class") == $(closestSection).attr("class"))
			return null;
		element = $(element).parent();
	}
}

function OnEnter(event, func) {
	var keynum;
	if (window.event) // IE
		keynum = event.keyCode;
	else if (event.which) // Netscape/Firefox/Opera
		keynum = event.which;

	if (keynum == 13) {
		func();
		return false;
	}
	return true;
}

/////////////////////////
///   LIFESTYLE       ///
/////////////////////////

$(document).ready(function() {
	$('#flashContainer .lifeStyles .category').each(function() {
		$(this).hover(function() {
			$(this).css({ 'opacity': '.5', 'filter': 'alpha(opacity=70)' });
		}, function() {
			$(this).css({ 'opacity': '1', 'filter': 'alpha(opacity=100)' });
		});
	});
	$('#flashContainer .lifeStyles .category:odd').addClass('odd');
	//$('.cookingReceipts .cookingImg .thumbnails img').click(function(){
	$('.cookingReceipts .cookingImg .thumbnails img').hover(function() {
		var url = $(this).attr('src');
		var exp = explode('_', url);
		var source = exp[0] + '.png';
		$('.cookingReceipts .cookingImg .full img').attr('src', source);
	});
});

function MultirowPick() {
	var $mrp = $('.Checkout .multirow_pick:has(input[type=radio])');
	if ($mrp.exists()) {
		$mrp.each(function() {
			var $el = $(this);
			var $name = $el.find('input[type=radio]').attr('name');
			$el.find('input[type=radio]:checked').parent().addClass('selected');
			$el.find('input[name=' + $name + '], label').click(function() {
				$el.find('td').removeClass('selected').find('input[type=radio]:checked').parent().addClass('selected');
			});
		});
	}
}

function BindToolTips() {
	$(".tooltip:has(span)").click(function() {
		var $alterBox = $(".alterBox");
		var $link = $(this);
		var $text = $link.find('span').attr('help');

		var clickOnPage = function(e) {
			var $parent = $(e.target).parent(".alterBox");
			if ($parent.length == 0) {
				$(".alterBox").remove();
				$link.removeClass("hover");
				$(document).unbind("click", clickOnPage);
			}
		};

		if ($link.hasClass("hover")) {
			$link.removeClass("hover");
			$alterBox.remove();
		}
		else {
			$alterBox.remove();

			$(".tooltip").removeClass("hover");
			$link.addClass("hover");
			$link.after('<div class="alterBox"><div class="alterBoxClose"></div><div class="alterBoxWrapper">' + $text + '</div></div>');
			$(".alterBox").appendTo("#container");
			var offset = $link.offset();
			var toleft = offset.left + 258 - $(".alterBox").width();
			var docwidth = $(document).width();
			var checkwidth = docwidth - toleft;
			if (checkwidth < 250) {
				$(".alterBox").addClass('alterBoxRight');
				toleft = toleft - 250;
			}
			$(".alterBox").css({
				'top': offset.top - 18 - $(".alterBox").height(),
				'left': toleft
			});
			$(".alterBox").find(".alterBoxClose").click(function() {
				$(".alterBox").remove();
			});

		}
		$(document).one("click", clickOnPage);

		return false;
	});
}

$(function() {
	BindToolTips();
	MultirowPick();
});

/////////////////////////
///   PROXY METHODS   ///
/////////////////////////
function postWebMethod(method, methodData, onSuccess) {
	$.ajax({
		type: "POST",
		contentType: "application/json; charset=utf-8",
		url: ROOT_URL + "Modules/Euronics/WebMethods.asmx/" + method,
		data: methodData,
		dataType: "json",
		success: function(data, status) {
			//alert(data);
			var s = "";
			for (var i in data['d'])
				s += i + " : " + data['d'][i] + "\n";
			//alert(s);
			onSuccess(data['d']);
		},
		error: function(data, status) {
			document.write(data["responseText"]);
		},
		timeout: function(data) {
			alert("Operation timed out!");
		}
	});
}

function ProductComparison_AddRemove(subGroupId, productId, checked, language) {
	if (!checked)
		$('#cbProductComparison_AddRemove_' + productId).removeAttr('checked');
	else {
		//remove other subgroup checks
		//$('.productComparisonToggle').not('.productComparisonGroup_' + subGroupId).removeAttr('checked');
	}

	postWebMethod(
        "ProductComparison_AddRemove",
        "{'subGroupId': " + subGroupId + ", 'productId': " + productId + ", 'wasChecked': " + checked + ", 'language': " + language + "}",
        function(data) {
        	if (data['ErrorMessage'] != null) {
        		alert(data['ErrorMessage']);
        		$('#cbProductComparison_AddRemove_' + productId).removeAttr('checked');
        	}
        	else
        		$('#uxProductsInComparison').html(data['Response']);
        }
        );
}

function Calculator_GetLeasePriceValue(providerId, price, categoryCode, periodInMonths, initialPayment, onSuccess) {
	postWebMethod(
    "Calculator_GetLeasePriceValue",
    "{'price': " + price + ", 'periodInMonths': " + periodInMonths + ", 'initialPayment': " + initialPayment + ", 'providerId':" + providerId + ", 'categoryCode':'" + categoryCode + "'}",
    onSuccess
    );
}

var _allTooltipsBind = false;

function BindAllTooltips(ajaxUrl) {
	if (!_allTooltipsBind && ajaxUrl) {
		_allTooltipsBind = true;
		var trans = new Array();
		$(".ajax > .tooltipContent").each(function() { trans.push($(this).html()); });
		//alert(trans.length);
		var params = {
			trans: trans
		};
		$.ajax({
			url: ajaxUrl,
			data: params,
			success: function(data) {
				$(".ajax > .tooltipContent").each(function() {
					var tooltip = data[$(this).html()];
					if (tooltip) {
						$(this).html(tooltip);
					} else {
						$(this).parent().hide();
					}
				});
			},
			dataType: "json"
		});
	}

	xOffset = 10;
	yOffset = 20;
	// these 2 variable determine popup's distance from the cursor
	// you might want to adjust to get the right result		
	/* END CONFIG */
	$("a.textTooltip, a.tooltip").hover(
		function(e) {
			var text = $(this).children(".tooltipContent").html();
			if (text == null)
				text = $(this).siblings(".tooltipContent").html();
			$("body").append("<div id='tooltip' >" + text + "</div>");
			$("#tooltip")
				.css("top", (e.pageY - xOffset) + "px")
				.css("left", (e.pageX + yOffset) + "px")
				.css("z-index", 20)
				.fadeIn("fast");
		},
		function() {
			$("#tooltip").remove();
		});
	$("a.textTooltip, a.tooltip").mousemove(function(e) {
		$("#tooltip")
		    .css("top", (e.pageY - xOffset) + "px")
		    .css("left", (e.pageX + yOffset) + "px");
	});
}

function calculateLease(providerId, sumElemId, periodElemId, depositElemId, retElementId, currency, categoryCode) {
	var price = parseInt($('#' + sumElemId).val());
	var periodInMonths = $('#' + periodElemId).val();
	var initialPayment = $('#' + depositElemId).val();
	Calculator_GetLeasePriceValue(providerId, price, categoryCode, periodInMonths, initialPayment, function(data) {
		var value = data ? data + ' ' + currency : '-';
		$('#' + retElementId).val(value);
	});
}

function AddToCart(productId, quantity, url, change_currency, sectionId, command, warranty, commit, retUrl, period) {
	//1. Show wait popup
	var bonusBox = $('#waitBox').clone();

	if ($('.blockUI .popUpBox').length == 1) {
		// 3. replace
		//$('.blockUI .popUpBox').hide('fast');
		bonusBox.hide();
		$('.blockUI .popUpBox').replaceWith(bonusBox);
		$('.blockUI .popUpBox').show();
	} else {
		$.blockUI({
			message: bonusBox,
			css: {
				width: '450px',
				textAlign: 'left'
			}
		});

		$('.blockOverlay').click($.unblockUI);
	}

	//2. Get add to cart popup
	$.ajax({
		url: url,
		type: 'POST',
		data: {
			ChangeCurrency: change_currency,
			ProductId: productId,
			Quantity: quantity,
			SectionId: sectionId,
			Command: command,
			UseWarranty: warranty,
			Commit: commit,
			ReturnUrl: retUrl,
			WarrantyPeriod: period
		},
		dataType: "json",
		success: function(data) {
			if (data.redirect) {
				// data.redirect contains the string URL to redirect to
				window.location.href = data.redirect;
			}
			else {
				//add all popups thus far
				if ($('.blockUI .popUpBox').length == 1) {
					// 3. replace
					//$('.blockUI .popUpBox').hide('slow');
					var newPopUpBox = $(data.html);
					newPopUpBox.hide();
					$('.blockUI .popUpBox').replaceWith(newPopUpBox);
					$('.blockUI .popUpBox').show();
				} else {
					//3.display popup
					$.unblockUI();

					$.blockUI({
						message: data.html,
						css: {
							width: '450px',
							textAlign: 'left'
						}
					});

					$('.blockOverlay').click($.unblockUI);
				}

			}
		}
	});
}


var clickEvent = function(e) {
	e.preventDefault();
	var button = $(this);
	$.unblockUI({
		onUnblock: function() {
			button.unbind('click', clickEvent);
			button.click();
			//eval($('#' + btnSuccessLinkId).attr('href'));
		}
	});
}

function updateRegisterForm() {
	return;
}

$.bind_custom_login_action = function(loginBtn) {

	$(document).ready(function() {
		$("a[rel^='popup[loginForm]']").click(function(btn) {
			var linkHeader = $(this).attr("title");
			var note = $("#loginFormNote");
			var header = $("#loginFormHeader");
			if (linkHeader) {
				header.hide();
				note.html(linkHeader);
				note.show();
			} else {
				note.hide();
				header.show();
			}

			$.blockUI({
				message: $('#loginForm'),
				css: {
					border: 'none',
					padding: '5px 10px 5px 5px',
					backgroundColor: '#fff',
					'-webkit-border-radius': '0px',
					'-moz-border-radius': '0px',
					opacity: 1,
					color: '#000',
					top: ($(window).height() - 150) / 2 + 'px',
					left: ($(window).width() - 400) / 2 + 'px',
					width: '400px',
					height: '207px'
				},
				constrainTabKey: false
			});
		})

		$(loginBtn).click(clickEvent);

		$(document).keypress(function(e) {
			if (e.keyCode == 27) $.unblockUI();
		});

		$('.blockOverlay').click($.unblockUI);
		$('#loginForm .cancel').click($.unblockUI);
	});

};

function updateScrollBars() {
	return;
}

function validationHelper(validationGroup) {
	return;
}

function activity_loader_ee(element, message) {

	var bonusBox = $('#waitBox').clone();

	if (message != null)
		bonusBox.find('.blueHeader').html(message);

	if ($('.blockUI .popUpBox').length == 1) {
	
		bonusBox.hide();
		$('.blockUI .popUpBox').replaceWith(bonusBox);
		$('.blockUI .popUpBox').show();
	} else {
		$.blockUI({
			message: bonusBox,
			css: {
				width: '450px',
				textAlign: 'left'
			}
		});

		$('.blockOverlay').click($.unblockUI);
	}
}

function activity_loader2(element) {
	return;
}

$.toggle = function() {

    var scrolledAreas = $(".shop_list, .holder");

    $("a[href='#toggle']").toggle(function() {

        var obj = $(this);
        var label = obj.attr("label");
        var text = obj.text();

        obj.text(label).attr("label", text);

        $("#" + $(this).attr("rel")).slideDown("normal", function() {

            scrolledAreas.jScrollPane();

        });


    }, function() {

        var obj = $(this);
        var label = obj.attr("label");
        var text = obj.text();

        obj.text(label).attr("label", text);

        $("#" + $(this).attr("rel")).slideUp("normal", function() {

            scrolledAreas.jScrollPane();

        });

    });

   };


   function fadeOutParent(element, after) {
   	var obj = $(element);
   	if (after)
   		obj.closest(".error_message").fadeOut("normal", after);
   	else
   		obj.closest(".error_message").fadeOut("normal");
   }

//   $(function() {
//   	$('.Checkout input[type = submit], .Checkout input[type = image], .searchIcon').each(function() {
//		$(this).click(function(obj) {
//   			$(this).attr("disabled", "disabled");
//   			return true;
//   		});
//   		var clickEvent = $(this).attr("onclick");
//   		if (clickEvent != null) {
//   			$(this).click(function(obj) {
//   				setTimeout(clickEvent, 0);
//   				return true;
//   			});
//   		}
//   	});
//   });
