﻿/// <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;
}

var clickEvent = function(e) {
	e.preventDefault();
	var button = $(this);
	$.unblockUI({
		onUnblock: function() {
			button.unbind('click', clickEvent);
			button.click();
		}
	});
}

$(function() {
	//$(document).pngFix();
});

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 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 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);
	});
});

/////////////////////////
///   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');

	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(price, periodInMonths, initialPayment, onSuccess) {
	postWebMethod(
    "Calculator_GetLeasePriceValue",
    "{'price': " + price + ", 'periodInMonths': " + periodInMonths + ", 'initialPayment': " + initialPayment + "}",
    onSuccess
    );
}