﻿// Initialize some useful global variables
// The locale variable is initialized by the CMS before inclusion of this
// script. If this is not the case, try extracting it from the URL path
if (typeof(locale) == "undefined")
//TODO: undo comment when url rewrite is fixed
//********************************************

//locale = window.location.pathname.split("/")[1];					//TODO: uncomment when url-rewrite is fixed

var index = window.location.pathname.indexOf("_");					//TODO: remove when url-rewrite is fixed 
locale = window.location.pathname.substring(index - 2,index + 3);	//TODO: remove when url-rewrite is fixed

languageCode = locale.split("_")[0];
countryCode = locale.split("_")[1];

s_account="leviseu" + countryCode.toLowerCase() + "dev"

var IE6 = false;

var strChUserAgent = navigator.userAgent;
var intSplitStart = strChUserAgent.indexOf("(",0);
var intSplitEnd = strChUserAgent.indexOf(")",0);
var strChMid = strChUserAgent.substring(intSplitStart, intSplitEnd);
var userEmail = "";

if(strChMid.indexOf("MSIE 6") != -1) IE6 = true;

// Group country codes into geographical regions
regions = new Array();
regions["BE"] = "EUROPE"; regions["IE"] = "EUROPE"; regions["FR"] = "EUROPE";
regions["PL"] = "EUROPE"; regions["AT"] = "EUROPE"; regions["FI"] = "EUROPE";
regions["CH"] = "EUROPE"; regions["RU"] = "EUROPE"; regions["CH"] = "EUROPE";
regions["GB"] = "EUROPE"; regions["SE"] = "EUROPE"; regions["IT"] = "EUROPE";
regions["DE"] = "EUROPE"; regions["CZ"] = "EUROPE"; regions["GR"] = "EUROPE";
regions["NL"] = "EUROPE"; regions["ES"] = "EUROPE"; regions["DK"] = "EUROPE";
regions["HU"] = "EUROPE"; regions["NO"] = "EUROPE"; regions["PT"] = "EUROPE";
regions["CH"] = "EUROPE";
regions["ID"] = "ASIA"; regions["NZ"] = "ASIA"; regions["IN"] = "ASIA";
regions["SA"] = "ASIA"; regions["MY"] = "ASIA"; regions["PH"] = "ASIA";
regions["VN"] = "ASIA"; regions["VN"] = "ASIA"; regions["CN"] = "ASIA";
regions["PK"] = "ASIA"; regions["SG"] = "ASIA"; regions["JP"] = "ASIA";
regions["HK"] = "ASIA"; regions["AU"] = "ASIA"; regions["AU"] = "ASIA";
regions["TH"] = "ASIA"; regions["KR"] = "ASIA"; regions["TW"] = "ASIA";
regions["EC"] = "SOUTH_AMERICA"; regions["PY"] = "SOUTH_AMERICA";
regions["UY"] = "SOUTH_AMERICA"; regions["CL"] = "SOUTH_AMERICA";
regions["PE"] = "SOUTH_AMERICA"; regions["VE"] = "SOUTH_AMERICA";
regions["CO"] = "SOUTH_AMERICA"; regions["MX"] = "SOUTH_AMERICA";
regions["AR"] = "SOUTH_AMERICA"; regions["CR"] = "SOUTH_AMERICA";
regions["BR"] = "SOUTH_AMERICA";
regionCode = regions[countryCode];
//if (regionCode == null)
//    alert("Unsupported country code: " + countryCode);

////////////////////////////////////////////////////////////////////////////////

var LevisShop = new Class({
	//LevisShop class should contain all functions that are used across the shop (not purchase or account)
    initialize: function(){
    	this.logLocation = "main";
    },
    clearProductFinderLastSearch: function() {
    	//cookie used to rebuild productlist in session
    	Cookie.write('REQUEST_HISTORY_QUERY', '',{path:'/'});
    	//reset some cookies in order to clear the last search performed on the gridpage
    	var cookie = Cookie.write('SEARCH_PARAMETERS', 'my_data', {path: '/'}); 
    	cookie.dispose();
    	Cookie.write('PRODUCT_VISUALIZATION', 'onmodel',{path:'/'});
    	logging.info(this.logLocation, "(clearProductFinderLastSearch) Cookies reset : 'SEARCH_PARAMETERS' & 'PRODUCT_VISUALIZATION'");
    },
    clearLastGlobalSearch: function() {
    	//cookie used to rebuild productlist in session
    	var cookie = Cookie.write('PARAM_LEVIS_QUERY', '', {path: '/'}); 
    	logging.info(this.logLocation, "(clearProductFinderLastSearch) Cookies reset : 'PARAM_LEVIS_QUERY'");
    },
    clearAllLastSearch: function() {
    	this.clearLastGlobalSearch();
    	this.clearProductFinderLastSearch();
    }, 
    navigateAndClearProductFinder: function(url) {
    	this.clearProductFinderLastSearch();
    	var topbottomCookie = Cookie.dispose('TOP_BOTTOM_SEARCH_STATE',{path:'/'});
    	window.location = url;
    }
  
});
var levisShop = new LevisShop();

// Highlights the appropriate nav button in the header
function highlightHeader () {
	var current_url = location.href;
	var toHighlight;
	if(current_url.indexOf("collections") > -1){
		toHighlight = $("header-collections");
	} else if(current_url.indexOf("news") > -1){
		toHighlight = $("header-news");
	} else if(current_url.indexOf("media") > -1){
		toHighlight = $("header-mediacenter");
	} else if(current_url.indexOf("store-locator") > -1){
		toHighlight = $("header-storelocator");
	} else if(current_url.indexOf("shop.eu.levi.com") > -1){
		toHighlight = $("header-shop");
	} else if(current_url.indexOf("shop") > -1){
		toHighlight = $("header-shop");
	} else {
		toHighlight = $("header-logo");
	}
	if (toHighlight)
		toHighlight.addClass("highlight");
}

function clearSearchField(event) {
    if (typeof(searchFocusFirstTime) == "undefined") {
		document.getElementById("search").value = "";
		searchFocusFirstTime = 1;
    }
}

function executeEshopSearch(){
	if($('search').value != "" && typeof(searchFocusFirstTime) != "undefined"){
		Cookie.dispose('GLOBAL_SEARCH_STATE',{path:'/'});
		var rootsearchpath= "/";
		if (window.location.hostname.indexOf("leviscratwork") != -1){
			rootsearchpath = "http://eu.levi.com/";
		}
		document.location.href = rootsearchpath + locale + "/search.html?levisQuery=" + escape($('search').value);
	}
	return false;
}

function searchKeyPressed(event) {
    var code;
    if (event.which == null)
	code = event.keyCode;    // IE
    else if (event.which > 0)
	code = event.which;      // All others

    if (code == 13 || code == 14)
	executeEshopSearch();
}

window.addEvent('domready', function() {
		highlightHeader();
		if ($('main') != null) {
			$('main').getElements('a.productFinderlink').each(function(link, index){
				link.addEvent('click', function() {
					levisShop.navigateAndClearProductFinder(link.get('href'));
					return false;
				});
			});
			$('main').getElements('#eshop-home-center div[class*=area] a').each(function(link, index){
				if (link.getAttribute('href') !=null && link.getAttribute('href').contains("/shop/products/")) {
					link.addEvent('click', function() {
						levisShop.navigateAndClearProductFinder(link.get('href'));
						return false;
					});
				}
			});
			
		};
		if ($('header') != null) {
			$('header').getElements('a').addEvent('focus', function(e) {
				e.target.blur();
			});
		}
		if ($('footer') != null) {
			$('footer').getElements('a').addEvent('focus', function(e) {
				e.target.blur();
			});
		}
});

/* This function says whether we're in Fatwire's InSite editing mode. It allows Javascript code to do different things in InSite */
function checkFatwireInsiteMode()
{
        return window.location.search.indexOf("rendermode=preview-") == -1 ? false : true;
}

function openPopup(url, parameters) {
	window.open(url, "LevisPopup", parameters);
}

function openMinimalPopup(url, parameters) {
	parameters += "status=0,toolbar=0,location=0,menubar=0";
	openPopup(url, parameters);
}

//deprecated function
function navigateAndClearProductFinder(url) {
	levisShop.navigateAndClearProductFinder(url);
}

/* clickable background setting */
window.addEvent('domready',function(){
	var myRequest = new Request({url: "/microsites/backgrounds-conf/backgrounds.conf", onSuccess: function(response){
		var backgrounds = eval(response);
		var url = window.location;
		var reg_home = /\/[a-zA-Z_]{5}\/index\.html/;
		var reg_collection = /\/[a-zA-Z_]{5}\/levis_collections\/levis\-jeans\.html#home/;
		var reg_shop = /\/[a-zA-Z_]{5}\/shop\/.*/;
		if(reg_home.test(url)){
			var background = backgrounds.homepage_background;
			var background_div = $(document.body);
			var background_child = $('main');
		}
		if(reg_collection.test(url)){
			var background = backgrounds.collection_background;
			var background_div = $(document.body);
			var background_child = $('main');
		}
		if(reg_shop.test(url)){
			var background = backgrounds.shop_background;
			var background_div = $('content');
			var background_child = $('eshop-content');
		}
		if(background && background.url){
			background_div.setStyle("background","black  url('"+background.url+"') center 0 "+background.repeat+"");
			if(background.link){
				background_div.setStyle("cursor","pointer");
				background_child.setStyle("cursor","default");
				background_div.addEvent('click',function(e){
					if(background.target == "blank")
						window.open(background.link,'new','toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
					else
						window.location = background.link;
				});
				background_child.addEvent('click',function(e){
					e.stopPropagation();
				});
			}
		}
	}}).get();
});

var msieversionResult = null;
function msieversion() {
	if (msieversionResult != null) {
		return msieversionResult;
	}
   var ua = window.navigator.userAgent
   var msie = ua.indexOf ( "MSIE " )

   if ( msie > 0 )     // If Internet Explorer, return version number
	   msieversionResult= parseInt (ua.substring (msie+5, ua.indexOf (".", msie )));
   else                 // If another browser, return 0
	   msieversionResult = 0;
   
   return msieversionResult;
}


function removeAmpFromUrl(url) {
    if(url.indexOf("?") != -1) {
        return url.substring(0,url.indexOf("?")).replace("&","") + url.substring(url.indexOf("?"));
    } else {
        return url.replace("&","");
    }
}

var initialHref = window.location.href;
Window.implement({
    getCleanUrl : function(){
    	//Add function to get a url withouth parameters
        var url = window.location.href;
        if (url.contains('?')) {
        	var reg = new RegExp("([^?]*).*", "g");
        	return reg.exec(url)[1];    
        } else {
        	return url;
        }
    },
    isPageRefreshed : function() {
    	//Check if the page was refreshed. (compare referer with the previous referer)
    	if (initialHref.contains("#f5")) {
    		return true;
    	} else {
    		return false;
    	}
    },
    isExternalLink : function(referer) {
    	//Check if the passed url is an external link
    	if (referer != null) {
	    	if (referer.indexOf('eu.levi.com') > -1 || 
	    		referer.indexOf('localhost') > -1 || 
	    		referer.indexOf('softlution.com') > -1) {
	    		return false;
	    	}
    	}
    	return true;
    },
    getPageName : function() {
    	if (window.location.pathname.lastIndexOf("/") != -1) {
    		if (window.location.pathname.length > window.location.pathname.lastIndexOf("/")) {
    			return window.location.pathname.substring(window.location.pathname.lastIndexOf("/") + 1);
    		}
    	} 
    	
    	return "";
    }
});


window.addEvent( 'keydown', function( evt ){ 
    if( evt.control && evt.alt && evt.key=='d') {
    	//alert('debugging started');
    	Cookie.write('ENABLE_LOGGING',"true",{path:'/'});
    }
}); 


var Logging = new Class({
    initialize: function(){
    	this.enabled = (Cookie.read('ENABLE_LOGGING') == 'true') && (console != null);
    },
    debug: function(loc,msg) {
    	if (this.enabled) {
    		console.debug(this.getOutputMsg(loc,msg));
    	}
    },
    error: function(loc,msg) {
    	if (this.enabled) {
    		console.error(this.getOutputMsg(loc,msg));
    	}
    },
    info: function(loc,msg) {
    	if (this.enabled) {
    		console.info(this.getOutputMsg(loc,msg));
    	}
    	
    },
    warn: function(loc,msg) {
    	if (this.enabled) {
    		console.warn(this.getOutputMsg(loc,msg));
    	}
    },
    infoObject: function(object) {
    	if (this.enabled) {
    		console.info(object);
    	}
    },
    getOutputMsg: function(loc,msg) {
    	return "[" + loc + "] " + msg;
    }, 
    enable: function(boolean) {
    	this.enabled = boolean;
    }
    
});
var logging = new Logging();
logging.info("main", "PageRefreshed : " + window.isPageRefreshed());
logging.info("main", "Previous page external: " + window.isExternalLink(document.referrer));


