
var _gaq = _gaq || [];
var s = new Array();
var isNotOffice = false;
var linkproductid = "";
var divpromo = "";
var superruperpromobool = true;
var HomeRedirect;
var LoginRedirect;
var OrdersRedirect;
var campaign = "";

$.ajaxSetup({
	type: "POST",
	contentType: "application/json; charset=utf-8",
	data: "{}",
	dataType: "json"
});

function trackEventHref(a, e, c, v) {
	if (isNotOffice) {
		_gaq.push(function () {
			var tracker = _gat._getTrackerByName();
			tracker._trackEvent(e, c, v);
			document.location = a.href;
		});
		return false;
	} else
		return true;
}

function initAjaxLinks() {
	$(window).unbind('popstate').bind('popstate', function (e) {
		if (e.originalEvent.state == null)//normal url
			return;
		showProductList(e.originalEvent.state, true);
	});
	$('a.ajaxPL').unbind('click').click(function (e) {
		var url = $(this).attr('href');
		reloadProductList(url);
		return false;
	});

	$('select.ajaxPL').unbind('change').change(function (e) {
		var url= this.options[this.selectedIndex].value;
		reloadProductList(url);
	});
}

function reloadProductList(url) {
	$('body').append('<img class="ajaxProgress" style="position:fixed;left:0;top:0;" src="/imgs/progress2.gif"/>');
	if (typeof (window.history.pushState) != 'function') {
		document.location = url;
	}
	else {
		$.ajax({
			url: "/Store/Services/StoreService.asmx/GetProductListAjax",
			data: $.toJSON({ urlToParse: url }),
			success: function (res) {
				res.url = url;
				showProductList(res);
			}
		});
	}
}

function showProductList(res, dontPush) {
	$('.contentPage').fadeTo(25, .5, function () {
		$('#productListContainer').replaceWith(res.d.productList);
		$('#plNav').replaceWith(res.d.navigation);
		$('#productListTitle').replaceWith(res.d.pageTitle);
		$('#breadCrumbContainer').replaceWith(res.d.breadCrumbs);

		document.title = res.d.htmlTitle;
		if (!dontPush)
			window.history.pushState(res, res.d.htmlTitle, res.url);
		$('.contentPage').fadeTo(50, 1);
		_gaq.push(['_trackPageview', res.url]);
		initAjaxLinks();
		$('.ajaxProgress').remove();
	});
}

function displayNewsletterPopup() {
    $(function () {
        showZoomLayerCouponing('newsletter');
        location.href = location.href.split('#')[0] + "#popup/newsletter";
    });
}
function displayCouponingPopup() {
	$(function () {

		//URL management
		var url = document.location.href;
		regUrl = new RegExp("^.*#popup/.*$", "");

		if (regUrl.test(url)) {
			var index = url.indexOf('#popup/') + 7;
			var couponingType = url.substr((index), (url.length - index));
			showZoomLayerCouponing(couponingType);
		}

		//Hyperlinks management
		$("a[href^='#popup/']").live('click', function () {
			var couponingType = $(this).attr('href').substr(7);
			showZoomLayerCouponing(couponingType);
		});
	});
}

function getIsOffice() {
	if (isNotOffice)
		return false;
	return true;
}

function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getQueryString(key) {
	s = window.location.search.substring(1);
	arr = s.split("&");
	for (i = 0; i < arr.length; i++) {
		pair = arr[i].split("=");
		if (pair[0].toLowerCase() == key) { return pair[1]; }
	}
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return (setStr);
}

function swfObjectCallback(e) {
	if (e.success)
		return;
	var hid = $('#' + e.id + '> input');
	var link = $('#' + e.id + '> a');
	var alt = link.text();
	var fallback = hid.val().split('|');
	link.empty().append('<img src="' + fallback[0] + '" alt="' + alt + ' height="' + fallback[2] + '" width="' + fallback[1] + '"/>');
}

function OnShoppingData(res) {

	var spanCount = $('#basketProductsCount');
	if (spanCount == null)
		return;
	spanCount.html(res.Quantity);

	var spanOrderOn = $('#spanOrderOn');
	var spanOrderOff = $('#spanOrderOff');
	if ((spanOrderOn == null) || (spanOrderOff == null))
		return;

	if (res.Quantity > 0) {
		spanOrderOn.show();
		spanOrderOff.hide();
	}
	else {
		spanOrderOn.hide();
		spanOrderOff.show();
	}

	var divMinicartContent = $('#v2_miniBasketContent ul');
	if (divMinicartContent == null || res.Quantity == 0)
		return;

	divMinicartContent.html(res.MiniCart);

	$('#newBasketPopup').html(res.Popup);

}
function UpdateMiniBasket() {

	var paramName = 'utm_source';
	var source = getQueryString(paramName);
	var fromCookie = getCookie(paramName);

	if (source != null && fromCookie == null) {
		var today = new Date();
		setCookie(paramName, source, (new Date(today.getTime() + (30 * 1000 * 60 * 60 * 24))).toGMTString(), '/', '', '');
		fromCookie = source;
	}

	$.ajax({
		url: "/Store/Services/StoreService.asmx/GetShoppingData",
		data: $.toJSON({ utm_source: fromCookie }),
		success: function (res) { OnShoppingData(res.d); }
	});
}

function ShowSubMenu(id) {
	node = $(".menuBig #" + id);
	node.append('<div class="lev2"></div>');
	node.find(' .lev2').html($("#submenu #_" + id).html());
	Show3LevelSubmenu();
}

function Show3LevelSubmenu() {
	$(".lev2 .point").hover(function () {
		$($(this).find(' .lev3')).show();
		return true;
	},

	    function () {
	    	$(this).find(' .lev3').hide();
	    	return true;
	    });

}

function openLayer(name) {
	$('#' + name).show();
}

function closeLayer(name) {
	$('#' + name).hide();
}


function openCloseLayer(name) {
	skn = document.getElementById(name).style;
	if (skn.display == "" || skn.display == "block") {
		skn.display = "none";
	} else {
		skn.display = "block";
	}
}

function switchId(nameOfId, numNumber, numOfEx) {
	for (i = 1; i < numNumber + 1; i++) {
		if (i != numOfEx) {
			if (document.getElementById(nameOfId + "_" + i) != null)
				document.getElementById(nameOfId + "_" + i).className = "inactive";
		} else {
			if (document.getElementById(nameOfId + "_" + i) != null)
				document.getElementById(nameOfId + "_" + i).className = "active";
		}
	}

}

function switchIdRubric(nameOfId, numNumber, numOfEx) {

	numNumber = numNumber * 10;
	for (i = numNumber + 1; i < numNumber + 4; i++) {
		if (i != numOfEx) {
			document.getElementById(nameOfId + "_" + i).className = "inactive";
		} else {
			document.getElementById(nameOfId + "_" + i).className = "active";
		}
	}
}

function switchLayer(nameOfId, numNumber, numOfEx) {
	var el;
	for (i = 0; i < numNumber + 1; i++) {
		if (document.getElementById(nameOfId + "_" + i) != null) {
			el = document.getElementById(nameOfId + "_" + i);
			if (el == null) continue;
			if (i != numOfEx) {
				el.style.display = "none";
			} else {
				el.style.display = "block";

			}
		}
	}
}



function switchLayerRubric(nameOfId, numNumber, numOfEx) {
	var el;
	numNumber = numNumber * 10;

	for (i = numNumber + 1; i < numNumber + 4; i++) {
		el = document.getElementById(nameOfId + "_" + i);
		if (el == null) continue;
		if (i != numOfEx) {
			el.style.display = "none";
		} else {
			el.style.display = "block";
		}
	}
}

function switchBrand(name) {
	var el1, el2;

	el1 = document.getElementById(name + "_AZ");
	el2 = document.getElementById(name + "_BrandRubric");

	if (el1.className == "inactive") {
		el2.className = "inactive";
		el1.className = "active";
	} else {
		el2.className = "active";
		el1.className = "inactive";
	}

}
function switchLayerBrand(name) {

	var el1, el2;

	el1 = document.getElementById(name + "_AZ").style;
	el2 = document.getElementById(name + "_BrandRubric").style;

	if (el1.display == "none") {
		el2.display = "none";
		el1.display = "block";
	} else {
		el2.display = "block";
		el1.display = "none";
	}
}

function toggleBrandDescription() {
    $('.brandDescriptionBlockText').toggle('slow');
    $("#hlLearnMore0").toggle('slow');
}

function upProduct(qteNum, nameForm, maxProduct) {
	if (caddie_upQte(qteNum, nameForm, maxProduct))
		_gaq.push(['_trackEvent', 'Product page', 'quantity', 'more', parseInt(qteNum)]);
}
function dwProduct(qteNum, nameForm, minProduct) {
	if (caddie_dwQte(qteNum, nameForm, minProduct))
		_gaq.push(['_trackEvent', 'Product page', 'quantity', 'less', parseInt(qteNum)]);
}
function upListItem(qteNum, nameForm, maxProduct) {
	if (caddie_upQte(qteNum, nameForm, maxProduct))
		_gaq.push(['_trackEvent', 'global', 'quantity', 'more', parseInt(qteNum)]);
}
function dwListItem(qteNum, nameForm, minProduct) {
	if (caddie_dwQte(qteNum, nameForm, minProduct))
		_gaq.push(['_trackEvent', 'global', 'quantity', 'less', parseInt(qteNum)]);
}

function caddie_upQte(qteNum, nameForm, maxProduct) {

	var input = $("#qte" + qteNum);
	var val = parseInt(input.val());
	if (val >= 999) {
		input.val(999);
		alert(maxProduct);
	}
	input.val(val + 1);
}

function caddie_dwQte(qteNum, nameForm, minProduct) {
	var input = document.getElementById("qte" + qteNum);
	if (input.value < 2) {
		alert(minProduct);
	}
	input.value--;
}

function galleryPhoto(DirOfImg) {

	document.images["zoom_big"].src = DirOfImg;

}

function list_openTr(trNum, infos) {
	tr_name = document.getElementById("tr_open" + trNum).style;
	tr_class = document.getElementById("tr_" + trNum);

	if (tr_name.display == "none") {
		tr_name.display = "";
		tr_class.className = 'lg_produit_on';

	} else {
		tr_name.display = "none";
		tr_class.className = 'lg_produit';
	}
}


function list_openRubricDescript() {
	tr_name = document.getElementById("RubricDescript").style;

	if (tr_name.display == "none") {
		tr_name.display = "";

	} else {
		tr_name.display = "none";
	}
}



function resizeListFour(pDiv1, pDiv2, pDiv3, pDiv4, pNumber) {
	$(document).ready(function () {
		var newClassName;
		for (i = 1; i < pNumber + 1; i++) {

			var detailDiv = $("#pdt_detail_" + i);
			if (!detailDiv.length) return;

			var nameTemp = detailDiv.attr('title');

			newClassName = "";
			if (i == pDiv1 || i == pDiv2 || i == pDiv3 || i == pDiv4) {
				newClassName = 'bloc_pdt_detail_left';
			} else {
				if (nameTemp == "kdo") {
					newClassName = 'bloc_pdt_detail_kdo';
				} else {
					newClassName = 'bloc_pdt_detail';
				}
			}

			detailDiv[0].className = newClassName;
		}

	});
}

function init_list(numNumber, pais) {


	if (document.all) {
		w = document.body.clientWidth + 17;
	} else {
		w = window.innerWidth;
	}


	if (w >= 1633) {
		resizeListFour(8, 16, '', '', numNumber);
	} else if (w >= 1431) {
		resizeListFour(7, 14, '', '', numNumber);
	} else if (w >= 1229) {
		resizeListFour(5, 10, 15, 20, numNumber);
	} else if (w < 1229) {
		resizeListFour(5, 10, 15, 20, numNumber);
	}


}


// positionner le panier et le zoom
function dimensionBackground(close, name) {
	$('#opac_layer').css({ left: 0, top: 0, 'width': $(window).width(), 'min-height': '100%' });
	$('#opac_layer').animate({ opacity: 0.5 }, 0);
	$('#opac_layer').unbind();
	if (close)
		$('#opac_layer').click(function () { close(); });
	else 
		$('#opac_layer').click(function () { 
			$('#opac_layer').fadeOut(600);
			if (name)
				$('#' + name).fadeOut(800);
		});
}

function dimensionPopup(name, divWidth, divHeight) {
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var windowScrollTop = $(window).scrollTop();
	if (divWidth == null)
		divWidth = $('#' + name).width();
	if (divHeight == null)
		divHeight = $('#' + name).height();

	var	x = windowWidth / 2 - divWidth / 2 ;
	var	y = windowHeight / 2 - divHeight / 2 + windowScrollTop;

	$('#' + name).css({ 'margin-left': x });
	$('#' + name).css({ 'margin-top': y });

	$('#' + name).css({ left: 0 });
	$('#' + name).css({ top: 0 });
}

function dimensionLayer(nLay) {
	dimensionBackground(function () {
		$('#' + nLay).fadeOut(600);
		$('#opac_layer').fadeOut(600);
	});
	dimensionPopup(nLay);
}

function TrackAndBuy(p) {
	BuyProduct(p, 1);
	if (isNotOffice) {
		_gaq.push(function () {
			var t = _gat._getTrackerByName();
			t._trackEvent('Page_list', 'buy_product');
		});
	}
}
function OnLookup(productID, quantity) {
    BuyProduct(productID, quantity);
}

function OnLookupAB(productID, quantity, version) {
    if (version == "b") {
        _gaq.push(['_trackEvent', 'Product page', 'add-to-cart-button-red']);
    } else {
        _gaq.push(['_trackEvent', 'Product page', 'add-to-cart-button-yellow']);
    }
    BuyProduct(productID, quantity);
}

function BuyProduct(productID, quantity) {

	var quantityserver;
	quantityserver = parseInt(quantity);

	$.ajax({
	    url: "/Store/Services/StoreService.asmx/AddToCart",
	    data: $.toJSON({ productID: productID, quantity: quantityserver }),
	    success: function (res) {
	        OnShoppingData(res.d);
	        setCookie('productaddedtocart', productID, (new Date(new Date().getTime() + (30 * 1000 * 60 * 60 * 24))).toGMTString(), '/', '', '');
	        setCookie('addedtocartproducturl', location.href, (new Date(new Date().getTime() + (30 * 1000 * 60 * 60 * 24))).toGMTString(), '/', '', '');
	        if (res.d.IsTest) {
	            openCartPopup();
	            _gaq.push(['_trackEvent', 'Buy product', 'add-to-cart-action-popup']);
	        }
	        else {
	            location.href = location.protocol + '//' + location.hostname + '/addtocart'
	            _gaq.push(['_trackEvent', 'Buy product', 'add-to-cart-action-page']);
	        }
	    }
	});
}

function slideDownMiniCart() {
	$('.v2_miniBasket').clearQueue().fadeIn(400);
}

function closeMiniCart(delay) {
	if (delay == null)
	    $('.v2_miniBasket').fadeOut(500);
    else
        $('.v2_miniBasket').delay(delay).fadeOut(500);
}
$('.v2_miniBasket .v2_miniBasketHide').live('click',function (e) {
    e.preventDefault();
    closeMiniCart();
});

function CampaignOnLookup(productID, CampaignName, quantity) {
	var quantityserver;
	quantityserver = parseInt(quantity);


	campaign = CampaignName.toLowerCase();
	if (campaign == 'siemens') campaign = 'gigaset'
	$.ajax({
		url: "/Store/Services/StoreService.asmx/AddToCartWithCampaign",
		data: $.toJSON({ productID: productID, quantity: quantityserver, CampaignName: campaign }),
		async: false
	});
	document.location = "/campaigns/" + campaign + "/checkout";
}

function UserSignOut(currentBase, NewBase, redirectTo) {
	document.location = currentBase + '/securelogin?o=p&b=' + NewBase + '&r=' + redirectTo;
}

function UpdateUserLogIn() {

	$.ajax({
		url: "/Store/Services/StoreService.asmx/LoadLoginControl",
		data: "{}",
		type: "POST",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (res) {
			OnUserLogInUpdated(res.d);
		}
	});
}


function OnUserLogInUpdated(result) {

	if (result == null)
		return;

	if (document.getElementById('HomeUserLogIn') != null) {
		if (result.Display) {
			document.getElementById('HomeUserLogIn').style.display = "none";
		}
		else {
			document.getElementById('HomeUserLogIn').style.display = "block";
		}
	}

	if (document.getElementById('UserLogIn') != null) {
		if (result.Control == null) {
			document.getElementById('UserLogIn').style.display = "none";
		}
		else {
			document.getElementById('UserLogIn').style.display = "block";
			$('#UserLogIn').html(unescape(result.Control));
		}
	}
}

// Gallery & New ProductList scrollers
jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
    return -c * ((t = t / d - 1) * t * t * t - 1) + b;
};

$(function () {
    if (typeof $('.gallery_list').serialScroll == 'function') {
        var $maxPage = $('#maxPage');
        var $prev = $('#galleryPrev').eq(0),
	        $next = $('#galleryNext').eq(0);

        var galleryPage = 1;

        $prev.click(function () {
            if (galleryPage > 1) {
                galleryPage--;
            }
            $('#galleryPageNb').html(galleryPage);
        });
        $next.click(function () {
            if (galleryPage < parseInt($maxPage.text())) {
                galleryPage++;
            }
            $('#galleryPageNb').html(galleryPage);
        });

        $('.gallery_list').serialScroll({
            items: '.gallery_displayPage .galleryPage',
            prev: '#galleryPrev',
            next: '#galleryNext',
            start: 0,
            duration: 1200,
            force: true,
            stop: true,
            lock: false,
            cycle: false,
            easing: 'easeOutQuart',
            onBefore: function (e, elem, $pane, $items, pos) {
                $prev.add($next).removeClass('disabled');
                if (pos == 0) {
                    $prev.addClass('disabled');
                } else if (pos == 0 && $items.length == 1) {
                    $prev.addClass('disabled');
                    $next.addClass('disabled');
                } else if (pos == $items.length - 1) {
                    $next.addClass('disabled');
                }
            }
        });
        if ($('.gallery_displayPage .galleryPage').length == 1) {
            $next.addClass('disabled');
        }
        $prev.addClass('disabled');
    }
    // New productList
    if (typeof $('.v2_mostPopularProducts .v2_slideshow').serialScroll == 'function') {
        var $prev2 = $('.v2_mostPopularProducts a.prev').eq(0),
			$next2 = $('.v2_mostPopularProducts a.next').eq(0);

        $('.v2_mostPopularProducts .v2_slideshow').serialScroll({
            items: 'li',
            prev: '.v2_mostPopularProducts a.prev',
            next: '.v2_mostPopularProducts a.next',
            offset: -185,
            start: 1,
            duration: 1200,
            force: true,
            stop: true,
            lock: false,
            cycle: false,
            easing: 'easeOutQuart',
            exclude: 2,
            onBefore: function (e, elem, $pane, $items, pos) {
                $prev2.add($next2).show();
                if (pos == 1)
                    $prev2.hide();
                else if (pos == $items.length - 3)
                    $next2.hide();
            }
        });

        $prev2.hide();
    }
});

function OnTabSimilarUpdated(result) {
	$('#SimilarProduct').html(unescape(result));
}

var similarProductsLoaded = false;
function AddSimilarProduct(Product_ID) {
	if (similarProductsLoaded) return;

	$('#SimilarProduct').html("<img alt='loading...' src='/imgs/progress.gif'  />");
	$.ajax({
		url: "/Store/Services/TabsProduct.asmx/AddTabsSimilarProduct",
		data: $.toJSON({ productID: Product_ID }),
		success: function (res) { OnTabSimilarUpdated(res.d); }
	});
	similarProductsLoaded = true;
}

var accessorProductsLoaded = false;
function AddAccessorProduct(Product_ID, productcampaign) {
	if (accessorProductsLoaded) return;

	accessorProductsLoaded = true;
	$('#AccessorProduct').html("<img alt='loading...' src='/imgs/progress.gif'  />");
	$.ajax({
		url: "/Store/Services/TabsProduct.asmx/AddTabsAccessorProduct",
		data: $.toJSON({ productID: Product_ID, productcampaign: productcampaign }),
		success: function (res) { OnTabAccessorUpdated(res.d); }
	});

}


function OnTabAccessorUpdated(result) {
	$('#AccessorProduct').html(unescape(result));
}


function PromoBlock(orderInList, OrderPromo, divfin) {
	this.orderInList = orderInList;
	this.OrderPromo = OrderPromo;
	this.divfin = divfin;
}

var arraypromoblock = new Array(24);
var orderInListPromo, OrderPromoPromo;


function AddPromoBlock(OrderPromo, Product_ID, orderInList, description, teaser, div) {

	if (superruperpromobool) {
		divpromo = div;
		orderInListPromo = orderInList;
		OrderPromoPromo = OrderPromo;


		var elem = orderInListPromo * 4 - OrderPromoPromo;

		if (arraypromoblock[elem] != null) {
			$('#' + divpromo).html(arraypromoblock[elem].divfin);
		}
		else {

			superruperpromobool = false;
			$('#' + divpromo).html("<br/><img alt='loading...' src='/imgs/progress.gif'  />");
			$.ajax({
				url: "/Store/Services/HomePage.asmx/AddPromoBlock",
				data: $.toJSON({
					productID: Product_ID,
					orderInList: orderInList,
					description: escape(description),
					teaser: teaser
				}),
				success: function (res) { OnPromoBlockUpdated(unescape(res.d)); }
			});
		}

	}

}

function OnPromoBlockUpdated(result) {
	if (!superruperpromobool) {
		superruperpromobool = true;
		$('#' + divpromo).html(result);
		var elem = orderInListPromo * 4 - OrderPromoPromo;
		arraypromoblock[elem] = new PromoBlock(orderInListPromo, OrderPromoPromo, result)
	}
}

function AddRubricPromoBlock(OrderPromo, Product_ID, orderInList, div) {

	if (superruperpromobool) {

		divpromo = div;
		orderInListPromo = orderInList;
		OrderPromoPromo = OrderPromo;

		var elem = orderInListPromo * 4 - OrderPromoPromo;

		if (arraypromoblock[elem] != null) {
			$('#' + divpromo).html(arraypromoblock[elem].divfin);
		}
		else {

			superruperpromobool = false;
			$('#' + divpromo).html("<br/><img alt='loading...' src='/imgs/progress.gif'  />");

			$.ajax({
				url: "/Store/Services/HomePage.asmx/AddRubricPromoBlock",
				data: $.toJSON({
					productID: Product_ID,
					orderInList: orderInList
				}),
				success: function (res) { OnRubricPromoBlockUpdated(unescape(res.d)); }
			});

		}
	}

}

function OnRubricPromoBlockUpdated(result) {
	if (!superruperpromobool) {
		superruperpromobool = true;
		$('#' + divpromo).html(result);
		var elem = orderInListPromo * 4 - OrderPromoPromo;
		arraypromoblock[elem] = new PromoBlock(orderInListPromo, OrderPromoPromo, result)
	}
}

////////////////////////////Comparar





function compareProducts(compare, Compare_Alert, Compare_4Alert) {
	var productparams = "?id=";
	var condicion = "";
	var separator = "";

	var boxValues = [];
	var boxes = $('input:checkbox[name=compareBox]');
	for (var i = 0; i < boxes.length; i++) {
		if ($(boxes[i]).is(':checked'))
			boxValues.push($(boxes[i]).val());
	}


	productparams += boxValues.join("%2C");

	if (boxValues.length < 2)
		alert(Compare_Alert);
	else if (boxValues.length > 4)
		alert(Compare_4Alert);
	else
		document.location.href = compare + productparams;
}

function isEmail(email) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(email);
}
var newsHidden = true;
function newsToggle() {
	if (newsHidden)
		newsPopupOpen();
	else
		newsPopupClose();
}

function newsPopupSetup() {
	var code = getQueryString("promo");
	if (code == null) code = '';
	$.ajax({
		url: '/Store/Services/StoreService.asmx/GetPromoHtml',
		data: $.toJSON({ code: code }),
		success: function (res) {
			if ($('#newsPopupCont')) {
				$('#newsPopupCont').html(unescape(res.d.html));
				if (screen.width > 1024) {
					$('#newsPopup').show();
					if (res.d.autoshow)
						newsShowPromo();
				}
			}
			$('#contactNumber').html(res.d.phone);
		},
		fail: function () { $('#newserror').show(); }
	});
}

function newsShowPromo() {
	newsPopupOpen();
	window.setTimeout(function () {
		$('#newsPopup').fadeOut(200).fadeIn(200, function () {
			window.setTimeout(function () { newsPopupClose(); }, 3000);
		});
	}, 1000);

}

function newsPopupOpen() {

	$('#newsPopup').animate({ left: '-240px' }, 200, function () {
		$('#newsPopup .promoPopup').show();
		$('#newsPopup').animate({ left: '0px' }, 700);
	});
	newsHidden = false;
}

function newsPopupClose() {
	$('#newsPopup').animate({ left: '-240px' }, 1000, function () {
		$('#newsPopup .promoPopup').hide();
		$('#newsPopup').animate({ left: '-220px' }, 200, function () {
			$('#newsresult').hide();
			$('#newserror').hide();
		});
	});
	newsHidden = true;

}
function PromoSubscribe() {
	var email = $('#promoSubscribe').val();
	if (!isEmail(email))
		$('#promoError').show();
	else {
		$.ajax({
			url: '/Store/Services/HomePage.asmx/AddNewsLetter',
			data: $.toJSON({ txtmail: email }),
			success: function () {
				$('#promoError').fadeOut(300);
				$('#promoResult').fadeIn(500, function () {
					window.setTimeout(function () { newsToggle(); }, 700);
				})
			},
			fail: function () { $('#promoError').show(); }
		});
	}
}
function ShowTab(id1, id2, count, order) {
	switchLayer(id1, count, order);
	switchId(id2, count, order);
}
function ShowHomeTab(count, order) {
	ShowTab('mask_contener', 'tabsid', count, order);
}

function ShowProductMediaTab(count, order) {
	ShowTab('media', 'detail_tab', count, order);
	//_gaq.push(['_trackEvent', 'Product page', 'product page rich content tabs', 'tab ' + order]);
	switch (order) {
	    case 1:
	        _gaq.push(['_trackEvent', 'Product page', 'product page rich content tabs', 'Image produit']);
	        break;
	    case 2:
	        _gaq.push(['_trackEvent', 'Product page', 'product page rich content tabs', 'Points forts']);
	        break;
	    case 5:
	        _gaq.push(['_trackEvent', 'Product page', 'product page rich content tabs', '3D']);
	        break;
	    default:
	        break;
	}
}
function ShowProductTab(order) {
	$(document).ready(function () {
	    ShowTab('detail', 'tabsid', 7, order); // Nota: No GA script in this function
        switch (order) {
            case 1:
                _gaq.push(['_trackEvent', 'Product page', 'product page navigation tabs', 'Fiche technique']);
                break;
            case 2:
                _gaq.push(['_trackEvent', 'Product page', 'product page navigation tabs', 'Avis clients']);
                break;
            case 3:
                _gaq.push(['_trackEvent', 'Product page', 'product page navigation tabs', 'Accessoires']);
                break;
            case 4:
                _gaq.push(['_trackEvent', 'Product page', 'product page navigation tabs', 'Nos Packs promo']);
                break;
            case 5:
                _gaq.push(['_trackEvent', 'Product page', 'product page navigation tabs', 'Grille tarifaire']);
                break;
            case 6:
                _gaq.push(['_trackEvent', 'Product page', 'product page navigation tabs', 'Produits similaires']);
                break;
            case 7:
                _gaq.push(['_trackEvent', 'Product page', 'product page navigation tabs', 'Onedirect']);
                break;
            default:
                break;
        }
	});
    $.scrollTo('div.v2_productTabs', 400);
	document.location.href = '#tab' + order;
}

function ShowReviews() {
	ShowProductTab(2);
}

function ShowAnchoredProductTab() {

	var url = document.location.toString();
	if (url.match('#tab')) {
		// the URL contains an anchor
		// click the navigation item corresponding to the anchor
		var i = url.split('#')[1].substring(3);
		ShowProductTab(i);
	}
}



function popupNewWindow(url) {
	window.open(url, '_blank', 'width=300, height=300, toolbar=0, location=0, directories=0, status=0, scrollbars=0', resizable = 'no', 'copyhistory=0, menuBar=0');
	return false;
}


//////////////////////////////////////////////////////// COD  CHAT /////////////////////////////////////////////////////////



var wv_vars = typeof (wv_vars) == "undefined" ? new Array() : wv_vars; wv_vars["ui_width"] = "430"; wv_vars["ui_height"] = "378"; wv_vars["ui_version"] = "UI0001"; wv_vars["ui_newwindow"] = "yes"; wv_vars["ui_accountid"] = "200106291793"; wv_vars["ui_host"] = "as00.estara.com"; wv_vars["ui_maxreferrer"] = 350; wv_vars["ui_window"] = null; wv_vars["ui_host_param"] = ""; if (typeof (eStara_startCobrowseGUINoFunc) == "undefined") { var eStara_startCobrowseGUINoFunc = 0; } wv_vars["ui_window"] = null; function webCall() { if (wv_vars["ui_window"] == null || wv_vars["ui_window"].closed) { var _1 = arguments; _1[_1.length++] = "calltype=webcall"; wv_vars["ui_window"] = wv_start(_1); } } function webCallBack() { var _2 = arguments; _2[_2.length++] = "calltype=webcallback"; wv_vars["ui_window"] = wv_start(_2); } function webVoicePop() { var _3 = arguments; _3[_3.length++] = "calltype=webvoicepop"; wv_start(_3); } function webSurveyPop() { var _4 = arguments; _4[_4.length++] = "calltype=websurveypop"; var _5 = wv_vars["ui_width"]; var _6 = wv_vars["ui_height"]; wv_vars["ui_width"] = 640; wv_vars["ui_height"] = 480; wv_vars["upload_only"] = 1; wv_start(_4); wv_vars["ui_width"] = _5; wv_vars["ui_height"] = _6; } function wv_checklinkstatus() { var _7 = "0"; for (var i = 0; i < arguments.length; i++) { var _9 = arguments[i].toString(); var _a = _9.indexOf("="); if (_a != -1) { var _b = (_9.substring(0, _a)).toLowerCase(); var _c = _9.substring(_a + 1, _9.length); switch (_b) { case "template": _7 = _c; break; } } } if ((typeof (wv_available_vars) != "undefined") && (typeof (wv_available_vars[_7]) != "undefined")) { return wv_available_vars[_7]; } else { return false; } } function wv_start(a) { var _e = navigator.userAgent.indexOf("MSIE") != -1; var _f = "webVoiceWindow"; if (_e) { _f = "_blank"; } var _10 = (window.location).toString(); var _11 = escape(_10); if (_11.length > wv_vars["ui_maxreferrer"]) { var _12 = _10.indexOf("?"); _10 = _12 > 0 ? _10.substring(0, _12) + "---TRUNCATED" : "UNAVAILABLE - URL IS TOO LONG"; _11 = escape(_10); if (_11.length > wv_vars["ui_maxreferrer"]) { _10 = "UNAVAILABLE - URL IS TOO LONG"; } } var _13 = typeof (document.title) != "undefined" ? document.title : "UNKNOWN"; if (escape(_13).toString().length > 255) { _13 = (document.title).toString().substring(0, 243) + "---TRUNCATED"; } var _14 = escape(_13); if (_14.length > 350) { _13 = "UNAVAILABLE - TITLE IS TOO LONG"; } var _15 = wv_vars["ui_newwindow"]; var _16 = wv_vars["ui_width"]; var _17 = wv_vars["ui_height"]; var _18 = wv_vars["ui_version"]; var _19 = wv_vars["ui_accountid"]; var _1a = ""; var _1b = ""; var _1c = ""; var _1d = ""; var _1e = (typeof (document.location.protocol) != "undefined" && document.location.protocol == "file:") ? "http" : ""; for (var i = 0; i < a.length; i++) { var _20 = a[i].toString(); var _21 = _20.indexOf("="); if (_21 != -1) { var _22 = (_20.substring(0, _21)).toLowerCase(); var _23 = _20.substring(_21 + 1, _20.length); switch (_22) { case "wndname": _f = _23; break; case "referrer": _10 = _23; break; case "pagetitle": _13 = _23; break; case "newwindow": _15 = _23; break; case "width": _16 = _23; break; case "height": _17 = _23; break; case "accountid": _19 = _23; break; case "wv_ui": _18 = _23; break; case "features": _1a = _23; break; case "baseurl": _1b = _23; break; case "protocol": _1e = _23; break; case "template": _1c = _23; _1d += "&" + _22 + "=" + escape(_23); break; case "ppwinname": if (_23 == "") { _23 = "PagePushWindow" + (new Date()).getTime() + Math.round(Math.random() * 1000000); this.name = _23; } default: _1d += "&" + _22 + "=" + escape(_23); break; } } else { alert("ERROR: Invalid argument passed to webXXX() function - Arg" + i + " is missing '=' sign : " + _20); return null; } } if (typeof (eStara_startCobrowseGUI) == "function") { eStara_startCobrowseGUI((wv_vars["upload_only"] == 1), _1c); } else { eStara_startCobrowseGUINoFunc = _1c; } for (var i = 1; i <= 10; i++) { eval("var eStara_assigned=(typeof(eStara_var" + i + ")!=\"undefined\"&&eStara_var" + i + "!=null)"); if (eStara_assigned) { eval("var eStara_tmp=\"&var" + i + "=\"+escape(eStara_var" + i + ");"); _1d += eStara_tmp; } } if (typeof (eStara_fsguid) != "undefined") { _1d += "&estara_fsguid=" + escape(eStara_fsguid); } if (_1e != "") { _1e += ":"; } if (_1b == "") { _1b = _1e + "//" + wv_vars["ui_host"] + "/UI/" + _18 + "/" + _18 + ".php"; } if (_1a == "") { _1a = "width=" + _16 + ",height=" + _17 + ",menubar=no,toolbar=no,directories=no,scrollbars=no,status=no,left=0,top=0,resizable=no"; } _1d = _1b + (_1b.indexOf("?") == -1 ? "?" : "&") + "donotcache=" + escape((new Date()).getTime()) + "&accountid=" + escape(_19) + "&referrer=" + escape(_10) + "&pagetitle=" + escape(_13) + wv_vars["ui_host_param"] + _1d; if ((typeof (wv_customurl) != "undefined") && (typeof (wv_customurl[_1c]) != "undefined") && (wv_customurl[_1c] != "")) { _1d = wv_customurl[_1c]; } if ((typeof (wv_customfeatures) != "undefined") && (typeof (wv_customfeatures[_1c]) != "undefined") && (wv_customfeatures[_1c] != "")) { _1a = wv_customfeatures[_1c]; } if (_15 != "yes") { window.location = _1d; } else { try { return window.open(_1d, _f, _1a); } catch (err) { } } return null; } function webChatPop() { var wv_argscopy = arguments; wv_argscopy[wv_argscopy.length++] = "wndname=eStaraChat_200106291793"; wv_argscopy[wv_argscopy.length++] = "calltype=webchatpop"; var prev_ui_width = wv_vars["ui_width"]; var prev_ui_height = wv_vars["ui_height"]; wv_vars["ui_width"] = 500; wv_vars["ui_height"] = 500; wv_start(wv_argscopy); wv_vars["ui_width"] = prev_ui_width; wv_vars["ui_height"] = prev_ui_height; }

function list_openRubricIndexLinks() {
	tr_name = document.getElementById("indexlinksresult").style;

	if (tr_name.display == "none") {

		$('#indexlinksresult').html($('#indexlinkscontent').html());
		tr_name.display = "";

	} else {
		tr_name.display = "none";
	}
}

function showZoomLayer(param) {
	$('#opac_text > div').hide()
	$('.opac_close').fadeIn(600);
	$('#' + param).fadeIn(600);
	$('#opac_layer').fadeIn(600);
	$('#opac_text').fadeIn(600);
	dimensionLayer('opac_text');
}

function showZoomLayerCampaigns(param) {
	document.getElementById('LinkParam').href = param;
	openLayer('opac_layer_campaign');
	openLayer('opac_text_campaign');
	dimensionLayerCampaigns('opac_text_campaign');
}

function showZoomLayerCampaignsBasket() {
	openLayer('opac_layer_campaign_basket');
	openLayer('opac_text_campaign_basket');
	dimensionLayerCampaigns('opac_text_campaign_basket');
}

function dimensionLayerCampaigns(nLay) {

	$(document).ready(function () {

		$('#opac_layer_campaign').css({ left: 0 });
		$('#opac_layer_campaign').animate({ opacity: 0.5 }, 0);

		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		var windowScrollTop = $(window).scrollTop();
		var divWidth = $('#' + nLay).width();
		var divHeight = $('#' + nLay).height();

		

		var totalWidth = windowWidth / 2 - divWidth / 2;
		var totalHeight = windowHeight / 2 - divHeight / 2 + windowScrollTop;


		$('#' + nLay).css({ 'margin-left': totalWidth });
		$('#' + nLay).css({ 'margin-top': totalHeight });

		$('#opac_layer_campaign').width($(document).width());
		$('#opac_layer_campaign').height($(document).height());


	});
}

//------------------------------------------------
//Begin Couponing

function showZoomLayerCouponing(couponingType) {
	BuildIFrame(couponingType);
}

function BuildIFrame(couponingType) {
	$('#opac_text_couponing').css({ padding: '5px', 'margin-top': '-1000px'});
	$('#iframeCouponing').attr({
		src: ('/Couponing/' + couponingType),
		width:0,
		height:0
	});
	openLayer('opac_text_couponing');
    ResizeCouponing(couponingType, null);
}
function ResizeCouponing(couponingType,_callback) {
    try{
    	$('#iframeCouponing').ready(function () {

    		$('#iframeCouponing').iframeAutoHeight({ callback: function () {
    			$('#opac_text_couponing .opac_close').show();
    			openLayer('opac_layer_couponing');
    			openLayer('opac_text_couponing');
    			CustomizeZoomLayerSize();
    		} 
    		});

    		var split = couponingType.split('?');
    		_gaq.push(['_trackEvent', 'Couponing', split[0].toLowerCase(), 'Viewed']);
    	});
        }
        catch(e){}
}

function CustomizeZoomLayerSize() {
	$('#opac_layer_couponing').css({ left: 0 });
	$('#opac_layer_couponing').animate({ opacity: 0.5 }, 0);

	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var windowScrollTop = $(window).scrollTop();

	var divWidth = $('#opac_text_couponing').width();
	var divHeight = $('#opac_text_couponing').height();

	var totalWidth =   Math.max(windowWidth / 2 - divWidth / 2 , 0);
	var totalHeight = Math.max(windowHeight / 2 - divHeight / 2 + windowScrollTop, 20);

	$('#opac_text_couponing').css({ 'margin-left': totalWidth });
	$('#opac_text_couponing').css({ 'margin-top': totalHeight });

	$('#opac_layer_couponing').width($(document).width());
	$('#opac_layer_couponing').height($(document).height());
}

//End Couponing
//------------------------------------------------

function GoToFilterResult(urlresult) {
	if (urlresult != null)
		window.location.href = urlresult;
}

function AddProductMessage(coments, worker, product, SKU, idTema, fileHash) {
	$.ajax({
		url: "/Store/Services/TabsProduct.asmx/AddProductMessage",
		data: $.toJSON({
			coments: coments,
			worker: worker,
			product: product,
			SKU: SKU,
			idTema: idTema,
			fileHash: fileHash
		}),
		async: false
	});
}

function SendProductMail(from, to, subject, body, fileHash) {
	$.ajax({
		url: "/Store/Services/TabsProduct.asmx/SendProductMail",
		data: $.toJSON({
			from: from,
			to: to,
			subject: subject,
			body: body,
			fileHash: fileHash
		}),
		async: false
	});
}

function DeleteProductMessage(idPk) {
	$.ajax({
		url: "/Store/Services/TabsProduct.asmx/DeleteProductMessage",
		data: $.toJSON({
			idPk: idPk
		}),
		async: false
	});
}

function GetProductMessages(SKU) {
	$('#ChatMesseges').html("<img alt='loading...' src='/imgs/progress.gif'  />");
	$.ajax({
		url: "/Store/Services/TabsProduct.asmx/GetProductMessages",
		data: $.toJSON({ reference: SKU }),
		success: function (res) { OnChatMessegesUpdated(res.d); }
	});
}

function OnChatMessegesUpdated(result) {
	$('#ChatMesseges').html(unescape(result.html));
	if (result.count > 0)
		$('#chat_table').tablesorter({ widgets: ['zebra'] });
}

function AddOnedirectTab(id, sku) {
	$.ajax({
		url: "/Store/Services/TabsProduct.asmx/GetOnedirectTab",
		data: $.toJSON({ reference: sku, id: id }),
		success: function (res) {
			if (res.d == null) {
				$('#tabsid_7').hide();
				return;
			}
			$('#tabsid_7').show();
			$('#tabsid_7_a span').text(res.d);

			InitUploader();
			GetProductMessages(sku);
		}
	});

}

function InitUploader() {
	var upload = $('#upload');
	upload.uploadify({
		'uploader': '/imgs/uploadify.swf',
		'script': '/store/uploads/uploadify.ashx',
		'cancelImg': '/imgs/cancel.png',
		'buttonImg': '/imgs/browse.png',
		'buttonText': 'Attach file...',
		'queueID': 'uploadQueue',
		'multi': false,
		'wmode': 'transparent',
		'width': ($.browser.msie ? "94px" : "'94px'"),
		'height': ($.browser.msie ? "22px" : "'22px'"),
		onComplete: function (event, queueID, fileObj, response, data) {
			$('#customQueue').hide();
			PostMessage(response);
		},
		onCancel: function () {
			$('#customQueue').hide();
		},
		onSelect: function (event, queueID, fileObj) {
			$('#fileName').html(fileObj.name);
			$('#customQueue').show();
		}

	});
}


function DeleteMessage(idPk) {
	DeleteProductMessage(idPk);
	GetProductMessages('<%= SKU %>');
}

function watermark(name, text) {
	var watermark = text;
	if ($(name).val() == "") {
		$(name).val(watermark);
	}
	$(name).focus(function () {
		if (this.value == watermark) {
		    this.value = "";
		    this.style.color='#999';
		}
	}).blur(function () {
		if (this.value == "") {
		    this.value = watermark;
		    this.style.color = '#bfbdc5';
		}
	});
}

$(function () {

    //-----------------------------
    //           NEW MENU
    //-----------------------------

    $('a.v2_more').mouseover(function () {
        $(this).next(['.test']).show();
    });

    $('a.v2_more').mouseleave(function () {
        $(this).next(['.test']).hide();
    });

    $('.v2_miniBasketContent').mouseleave(function () {
        closeMiniCart(2000);
    });

    $('.expandMiniCart').click(function (e) {
        e.preventDefault();
        if ($('.v2_miniBasketContent li').length > 0)
            slideDownMiniCart();
    });

    //-----------------------------
    //         END NEW MENU
    //-----------------------------

    //-----------------------------
    //          NEW RUBRIC
    //-----------------------------

    //slide more
    if ($('a.v2_points'.length != 0)) {
        $('a.v2_points').click(function (e) {
            e.preventDefault();
            $('.v2_pointsSel').removeClass('v2_pointsSel');
            $(this).parents().eq(3).addClass('v2_pointsSel');
            $(this).parents().eq(3).find('.v2_pointsMore').toggle();
        });
    }

    //-----------------------------
    //        END NEW RUBRIC
    //-----------------------------
});

//---------------------------------
//          NEW MY ACCOUNT
//---------------------------------

function negociated_upQte(inputId) {
    var ctrl = $('#' + inputId);
    var val = parseInt(ctrl.val());
    if (val >= 999) {
        ctrl.val(999);
    }
    else {
        ctrl.val(val + 1);
    }
}

function negociated_dwQte(inputId) {
    var ctrl = $('#' + inputId);
    var val = parseInt(ctrl.val());
    if (val > 0) {
        ctrl.val(val - 1);
    }

}

function updateValidation(control, validator1, validator2, validator3) {
    if (typeof (Page_Validators) == "undefined") return;
    var valid = true;
    ValidatorValidate(validator1);
    if (!validator1.isvalid) {
        valid = false;
    }
    if (typeof validator2 != 'undefined' && valid) {
        ValidatorValidate(validator2);
        if (!validator2.isvalid) {
            valid = false;
        }
    }

    if (typeof validator3 != 'undefined' && valid) {
        ValidatorValidate(validator3);
        if (!validator3.isvalid) {
            valid = false;
        }
    }

    var ctrl = control;

    if (valid) {
        if ($(ctrl).parent()[0].tagName == "SPAN") {
            $(ctrl).parent().parent().removeClass("errorArrow").addClass("validationSuccess");
        }
        else {
            $(ctrl).parent().removeClass("errorArrow").addClass("validationSuccess");
        }
    }
    else {
        if ($(ctrl).parent()[0].tagName == "SPAN") {
            $(ctrl).parent().addClass('error');
            $(ctrl).parent().parent().addClass("errorArrow");
            $(ctrl).parent().parent().removeClass("validationSuccess");
        }
        else {
            $(ctrl).addClass('error');
            $(ctrl).parent().addClass("errorArrow");
            $(ctrl).parent().removeClass("validationSuccess");
        }
    }

}

function showHelp(control) {
    var ctrl = control;
    hideHelp(control);
    var parent = $('#' + ctrl).parent();
    var error = parent.children('.error');
    if (error.length > 0 && parent.attr('class') != 'validationSuccess') {
        for (var i = 0; i < error.length; i++) {
            if ($(error[i]).css('display') != 'none') {
                return;
            }
        }
        $('#' + ctrl).css('display', 'block');
    }
    else {
        $('#' + ctrl).css('display', 'block');
        return;
    }
}

function hideHelp(control) {
    var ctrl = control;
    if (typeof $('#' + ctrl) != 'undefined') {
        $('#' + ctrl).css('display', 'none');
    }
}

function ValidatePage(validationGroup) {
    //Executes all the validation controls associated with a validation group
    var summaryInformation = Page_ClientValidate(validationGroup);
    var ValidatorsInfo = GetInvalidValidators(validationGroup);

    return DisplayValidators(validationGroup, summaryInformation, ValidatorsInfo);
}

function DisplayValidators(validationGroup, summaryInformation, ValidatorsInfo) {

    if (summaryInformation)
        return true;
    else {
        var errorFound = false;

        jQuery('.defaultErrorBox').each(function () {
            var arLen = ValidatorsInfo.length;
            for (var i = 0, len = arLen; i < len; ++i) {
                if (jQuery(this).parent().attr('id') == jQuery(ValidatorsInfo[i]).attr('id')) {
                    if (!errorFound) {
                        jQuery(this).parent().addClass('error');
                        errorFound = true;
                    }
                    else {
                        jQuery(this).parent().parent().removeClass('errorArrow');
                        jQuery(this).parent().css('display', '');
                    }
                }
            }
        });
    }
    return false;
}

function GetInvalidValidators(validationGroup) {
    var validatorArray = new Array();

    for (var i = 0; i < Page_Validators.length; i++) {
        var validator = Page_Validators[i];
        if (validator.validationGroup == validationGroup && validator.isvalid == false) {
            validatorArray.push(validator);
        }
    }

    return validatorArray;
}

function GetAllValidators(validationGroup) {
    var validatorArray = new Array();

    for (var i = 0; i < Page_Validators.length; i++) {
        var validator = Page_Validators[i];
        if (validator.validationGroup == validationGroup) {
            validatorArray.push(validator);
        }
    }

    return validatorArray;
}

function ValidatePageAtLoad(validationGroup) {
    //Executes all the validation controls associated with a validation group
    var summaryInformation = Page_ClientValidate(validationGroup);
    var ValidatorsInfo = GetInvalidValidators(validationGroup);
    var allValidators = GetAllValidators(validationGroup);

    return DisplayValidEntries(validationGroup, summaryInformation, ValidatorsInfo, allValidators);
}

function DisplayValidEntries(validationGroup, summaryInformation, ValidatorsInfo) {

    jQuery('.defaultErrorBox').each(function () {
        var arLen = ValidatorsInfo.length;
        if (arLen > 0) {
            for (var i = 0, len = jQuery('.defaultErrorBox').length - arLen; i < len; ++i) {
                if (jQuery(this).parent().attr('id') == jQuery(ValidatorsInfo[i]).attr('id')) {
                    // Don't process
                }
                else {
                    for (var j = 0, len2 = allValidators.length; j < len2; ++i) {
                        if (jQuery(this).parent().attr('id') == jQuery(allValidators[i]).attr('id') && jQuery(this).parent().Text != null) {
                            jQuery(this).parent().parent().addClass('validationSuccess');
                        }
                    }
                }
            }
        }
        else {
            if ($(this).parent().attr('class') != 'helpLeft' && $(this).parent().attr('class') != 'helpBottom') {
                if ($($($(this).parent()).siblings()[0]).is("input") && $($($(this).parent()).siblings()[0]).attr('value') != "" && $($($(this).parent()).siblings()[0]).attr('value') != " ")
                    jQuery(this).parent().parent().addClass('validationSuccess');
                else if ($($($(this).parent()).siblings()[0]).is("input") == false)
                    jQuery(this).parent().parent().addClass('validationSuccess');
            }
        }
    });
}

function showForgotPassword() {
    openLayer('opac_layer_accountBox');
    openLayer('opac_accountBox');
    dimensionLayerForgotPassword('opac_accountBox');
}

function dimensionBackgroundForgotPassword(close) {
    $('#opac_layer_accountBox').css({ left: -332 });
    $('#opac_layer_accountBox').css({ top: 0 });
    $('#opac_layer_accountBox').width($(document).width());
    $('#opac_layer_accountBox').height($(document).height());
    $('#opac_layer_accountBox').animate({ opacity: 0.5 }, 0);
    $('#opac_layer_accountBox').unbind();
    if (close)
        $('#opac_layer_accountBox').click(function () { close(); })
}

function dimensionPopupForgotPassword(name, divWidth, divHeight) {
    var windowWidth = $(window).width();
    var windowHeight = $(document).height();
    var windowScrollTop = $(window).scrollTop();
    if (divWidth == null)
        divWidth = $('#' + name).width();
    if (divHeight == null)
        divHeight = $('#' + name).height();

    var totalWidth = windowWidth - divWidth;
    var totalHeight = windowHeight - divHeight + windowScrollTop;

    $('#' + name).css('margin-left', '0px');
    $('#' + name).css('margin-top', '100px');

    $('#' + name).css({ left: 248 });
    $('#' + name).css({ top: 140 });
}

function dimensionLayerForgotPassword(nLay) {

    $(document).ready(function () {
        dimensionBackgroundForgotPassword(function () {
            $('#' + nLay).fadeOut(600);
            $('#opac_layer_accountBox').fadeOut(600);
        });
        dimensionPopupForgotPassword(nLay);
    });
}

//---------------------------------
//        END NEW MY ACCOUNT
//---------------------------------

//---------------------------------
//      BEGIN POP IN MANAGER
//---------------------------------
function openPopupNoMask(name) {
	showPopin(name, null, null, null, null, null, null, null, null, null, true);
}

function openPopup(name) {
    showPopin(name, 'opac_layer', null, null, null, null, null, null, null, null, true);
}

function closePopup(name) {
    $('#opac_layer').fadeOut(800);
    $('#' + name).fadeOut(600);
}

function openCartPopup() {
    showPopin('newBasketPopupBox', 'opac_layer', null, null, null, null, 300, null, null, closeCartPopup, false);
}

function closeCartPopup() {
    _gaq.push(['_trackEvent', 'confirmation popup', 'continue']);
    $('#opac_layer').fadeOut(800);
    $('#newBasketPopupBox').fadeOut(600);
}

function showGalleryPopin() {
    showPopin('opac_text_gallery', 'opac_layer_gallery', 'opac_close', null, null, 0, 100, 0, 0, null, false);
}

function closeMainPopin(oLay, oLayBox) {
    $('#' + oLay).fadeOut(600);
    $('#' + oLayBox).fadeOut(600);
}

function showPopin(oLay, oLayBox, oClose, nDivWidth, nDivHeight, nLayWidth, nLayHeight, nLeftValue, nTopValue, nCloseFunc, nCenterToWindowPos) {
    // INFO :
    // oLay : The pop-in content layer
    // oLaybox : The pop-in background layer (the dark background)
    // divWidth : Used in mainDimensionPopup to position the pop-in on the document (may be null - default = oLay width)
    // divHeight : Used in mainDimensionPopup to position the pop-in on the document (may be null - default = oLay height)
    // layWidth : Fixed margin Left of the pop-in (may be null - default = 0)
    // layHeight : Fixed margin Top of the pop-in (may be null - default = 0)
    // leftValue : Fixed absolute Left of the pop-in (may be null - default = 0)
    // topValue : Fixed absolute Top of the pop-in (may be null - default = 0)
    // closeFunc : Close function used when clicking on the background (may be null - default closeMainPopin(oLay, oLayBox))
    // centerToWindowPos : Boolean that forces or not the positionning of the pop-in in the center of the window
    
    if (oClose != null)
    	$('.' + oClose).show();
 if (oLayBox)
     $('#' + oLayBox).fadeIn(800, function () {
         $('#' + oLay).fadeIn(600);
         mainDimensionLayer(oLay, oLayBox, nDivWidth, nDivHeight, nLayWidth, nLayHeight, nLeftValue, nTopValue, nCenterToWindowPos, nCloseFunc);
     });
    
}

// positionner le panier et le zoom
function mainDimensionLayer(nLay, nOLayBox, nDivWidth, nDivHeight, nLayWidth, nLayHeight, nLeftValue, nTopValue, nCenterToWindowPos, nCloseFunc) {
	$(document).ready(function () {
		mainDimensionPopup(nLay, nDivWidth, nDivHeight, nLayWidth, nLayHeight, nLeftValue, nTopValue, nCenterToWindowPos);
		if (nOLayBox == null)
			return;
		if (nCloseFunc != null) {
			mainDimensionBackground(nCloseFunc, nOLayBox);
		}
		else {
			mainDimensionBackground(function () {
				$('#' + nLay).fadeOut(600);
				$('#' + nOLayBox).fadeOut(600);
			}, nOLayBox);
		}
	});
}


function mainDimensionBackground(close, oLay) {
    $('#' + oLay).css({ left: 0 });
    $('#' + oLay).width($(document).width());
    if ($(document).height() < $(window).height()) {
        $('#' + oLay).height($(window).height());
    }
    else {
        $('#' + oLay).height($(document).height());
    }
    $('#' + oLay).animate({ opacity: 0.5 }, 0);
    $('#' + oLay).unbind();
    if (close)
        $('#' + oLay).click(function () { close(); });
    else
        $('#' + oLay).click(function () { $('#' + oLay).fadeOut(600); });
}

function mainDimensionPopup(name, divWidth, divHeight, marginLeft, marginTop, leftVal, topVal, centerToWindowPos) {
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    var windowScrollTop = $(window).scrollTop();

    var totalWidth;
    var totalHeight;

    if (centerToWindowPos || (marginLeft == null && marginTop == null)) {
        if (divWidth == null)
            divWidth = $('#' + name).width();
        if (divHeight == null)
            divHeight = $('#' + name).height();

        totalWidth = windowWidth / 2 - divWidth / 2;
        totalHeight = windowHeight / 2 - divHeight / 2 + windowScrollTop;
        if (totalWidth < 0) totalWidth = 0;
        if (totalHeight < 0) totalHeight = 0;
    }
    else {
        if (marginLeft != null)
            totalWidth = marginLeft;
        else
            totalWidth = 0;
        
        if (marginTop != null)
            totalHeight = marginTop + windowScrollTop;
        else
            totalHeight = 0;
    }

    $('#' + name).css('margin-left', totalWidth + 'px');
    $('#' + name).css('margin-top', totalHeight + 'px');

    if (leftVal != null) {
        $('#' + name).css({ left: leftVal });
    }
    else {
        $('#' + name).css({ left: 0 });
    }
    if (topVal != null) {
        $('#' + name).css({ top: topVal });
    }
    else {
        $('#' + name).css({ top: 0 });
    }
}

function AddProductCookie(productID) {
    var lastSeen = getCookie('lastseenproducts');
    if (lastSeen == null) lastSeen = '';
    var products = lastSeen.split(':');
    var count = products.length > 10 ? 10 : products.length;
    lastSeen = productID;
    for (i = 0; i < count; i++) {
        if (products[i] != productID && products[i]!='')
            lastSeen += (':' + products[i]);
    }
    setCookie('lastseenproducts', lastSeen, (new Date(new Date().getTime() + (30 * 1000 * 60 * 60 * 24))).toGMTString(), '/', '', '');
}
function ProcessAddToCartPage() {
    var productaddedtocart = getCookie('productaddedtocart');
    if (productaddedtocart == null) {
        location.href = location.protocol + '//' + location.hostname + '/';
        return;
    }
    var lastseenproducts = getCookie('lastseenproducts');
    if (lastseenproducts == null) lastseenproducts = '';

    $.ajax({
        url: "/Store/Services/StoreService.asmx/GetAddToCartPage",
        data: $.toJSON({ productID: productaddedtocart, lastseen: lastseenproducts }),
        success: function (res) {
            $('#info').html(res.d);
            var backurl = getCookie('addedtocartproducturl');
            if (backurl != null && backurl.indexOf('/addtocart')==-1) $('#backurl').attr('href', backurl);
        }
    });
}
