var defaultCity = 'moskva';

/*----------------------begin cookie help functions-----------------*/
function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + encodeURI(value) + ((expiredays == null) || (expiredays == 0) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/";
}

function getCookie(name) {
    var dcookie = document.cookie;
    var cname = name + "=";
    var clen = dcookie.length;
    var cbegin = 0;
    while (cbegin < clen) {
        var vbegin = cbegin + cname.length;
        if (dcookie.substring(cbegin, vbegin) == cname) {
            var vend = dcookie.indexOf(";", vbegin);
            if (vend == -1) vend = clen;
            return decodeURI(dcookie.substring(vbegin, vend));
        }
        cbegin = dcookie.indexOf(" ", cbegin) + 1;
        if (cbegin == 0) break;
    }
    return null;
}
/*----------------------begin cookie help functions-----------------*/

/*------------------------------------------- -=Direct filter block=- ------------------------------------------------*/
//set city on page according to rule:
//if city was in xml -> use it and set it to cookie
//else use cookie city
function getCheckedCity(){
    var checkedCity = null;
    if(document.getElementById("checkedCity") && document.getElementById("checkedCity").innerHTML != ""){
        checkedCity = document.getElementById("checkedCity").innerHTML;
    }
    var city = getCookie("city");
    if (checkedCity == city || city == null) {
        //update page city from cookie
        if(document.getElementById(defaultCity) != null){
            getCity();            
        }
    } else if (checkedCity) {
        //set old city to cookie
        setCookie("city", checkedCity, 1000);
    }
}

function getCity() {
    var city = getCookie("city");

    if (city) {
    	var citySpan = document.getElementById(city);
    	citySpan.style.display = 'none';
    	document.getElementById("cityValue").innerHTML = citySpan.innerHTML + " ";
    }

	if (document.getElementById('alternativeCityChange')) {
		if (city) {
			document.getElementById('alternativeCityChange').value = city;
		} else {
			document.getElementById('alternativeCityChange').value = defaultCity;
		}
	} else {
		if (getCookie("oldCity")) {
			returnCity();
			document.location.reload(true);
		}
	}
}

function setCity(city) {
    setCookie("city", city, 1000);

    document.location.reload(true);
}

function returnCity() {
	var oldCity = getCookie("oldCity");

	setCookie('city', oldCity, 1000);
	setCookie('oldCity', '', 0);
}

function toggleMenu() {    
    if (document.getElementById("cityList").style.display == "none") {
        document.getElementById("cityList").style.display = "";
        document.getElementById("selectedCity").onmouseout = '';
        document.getElementById("selectedCity").onmouseover = '';
    } else {
        document.getElementById("cityList").style.display = "none";        
        document.getElementById("selectedCity").onmouseout = function(){drawMenuBorder();};
        document.getElementById("selectedCity").onmouseover = function(){drawMenuBorder();};       

    }
}

function drawMenuBorder(){
    if(document.getElementById('selectedCity').className == "withBorder"){
        document.getElementById('selectedCity').className = "";
    }else{
        document.getElementById('selectedCity').className = "withBorder";
    }
}

function drawCityFill(el){
    if(el.className == "mouseOver"){
        el.className = "";
    }else{
        el.className = "mouseOver";
    }    
}

/**
 * Check if user have 'city' cookie.
 * If user does't have 'city' cookie - try detect user city by ip-address.
 * @return
 */
function checkUserGeo() {
	var city = getCookie("city");
	if (!city) {
		CommonDWR.findUserCity(findUserCityCallback);
	}
}

function findUserCityCallback(data) {
	if (data) {
		setCookie("city", data, 1000);
		document.location.href = document.location.href;
	} else {
		/**
		 * Set default city, to reduce amount of dwr request.
		 * No redirect, pages by default filters with city='moskva'
		 */
		setCookie("city", defaultCity, 1000);
	}
}

/*------------------------------------------- -=Direct filter block=- ------------------------------------------------*/

/*------------------------------------------- -=Send error block=- ---------------------------------------------------*/

function checkErrorMessage(messId, errorMessId){
    var message = document.getElementById(messId).value;    
    var empty = message.replace(/^\s+|\s+$/g, '').length == 0;
    document.getElementById(errorMessId).style.display = empty ? "" : "none";
    return !empty;
}

/*------------------------------------------- -=Favourite group block=- --------------------------------------------------*/
function getCurrency() {
	var currencyElement = document.getElementById('currency');
	var currency = '';
	if (currencyElement) {
		currency = currencyElement.options[currencyElement.selectedIndex].value;
	}
	return currency;
}
/*------------------------------------------- -=Quick search block=- -------------------------------------------------*/

function stopEvent(ev) {
	if (ev.preventDefault) {
		ev.preventDefault();
		ev.stopPropagation();
	} else {
		ev.returnValue = false;
		ev.cancelBubble = true;
	}

}

function createForm(action, isPost) {
	var form = document.createElement('form');
	form.action = action;
	if (isPost) {
		form.method = 'post';
	} else {
		form.method = 'get';
	}
	document.getElementsByTagName('body')[0].appendChild(form);

	return form;
}

function addHiddenField(form, name, value) {
	var input = document.createElement('input');
	input.type = 'hidden';
	input.name = name;
	input.value = value;
	form.appendChild(input);
}

function keyValid(ev) {
	var keynum;
	var keychar;
	var numcheck;

	if (0 == ev.keyCode) {
        if (window.event) {
            keynum = ev.keyCode;
        }
        else if (ev.which) {
            keynum = ev.which;
        }
        keychar = String.fromCharCode(keynum);
        numcheck = /\D/;
        return !numcheck.test(keychar);
    } else if (document.all){
		if (window.event) {
			keynum = ev.keyCode;
		}

		keychar = String.fromCharCode(keynum);
		numcheck = /\D/;
		return !numcheck.test(keychar);
	} else {
        return true;
    }
}

function replaceNonNumeric(el) {
	el.value = el.value.replace(/\D/g,'');
}

function replaceNonDoubleNumeric(el) {
	el.value = el.value.replace(/^([^,.]*[,.][^,.]*)[,.]/g,'$1');
    el.value = el.value.replace(/[^0-9,.]/g,'');
    el.value = el.value.replace(/[,]/g,'.');
}

function addToClipboard(id) {
	window.clipboardData.setData("Text",document.getElementById(id).value);
}

function displayCopyToClipboard() {
    if (document.all) {
        if (document.getElementById('copyToClipboardButton')) {
            document.getElementById('copyToClipboardButton').style.display = '';
        }
    }
}

var showedLetterCard = null;
function showLetterCard(el) {
    if (null != showedLetterCard) {
        showedLetterCard.style.display = 'none';
        showedLetterCard.parentNode.getElementsByTagName('a')[0].style.display = '';
    }

    showedLetterCard = el.parentNode.getElementsByTagName('div')[0];
    el.parentNode.getElementsByTagName('a')[0].style.display = 'none';
    showedLetterCard.style.display = '';
}

/*--------------------begin news js-------------------------------------*/
function loadVideo() {
	VideoDWR.getVideo(document.getElementById('videoBrand').value, document.getElementById('videoPageNumber').value, function (html){
		document.getElementById('videoBlock').innerHTML = html;
	});
}

function showHideAddBrands(){
    if('noDisplay commonList'==document.getElementById('additionalBrands').className){
        document.getElementById('additionalBrands').className = 'commonList';
        document.getElementById('showAdditional').className = 'noDisplay';
        document.getElementById('hideAdditional').className = 'actionLink';
    }else{
        document.getElementById('additionalBrands').className = 'noDisplay commonList';
        document.getElementById('showAdditional').className = 'actionLink';
        document.getElementById('hideAdditional').className = 'noDisplay';
    }

}

if (document.getElementById('videoBlock')) {
	if (document.addEventListener) {
		window.addEventListener('load', loadVideo, false);
	} else if (document.attachEvent) {
		window.attachEvent('onload', loadVideo);
	}
}
/*--------------------end news js-------------------------------------*/

function masterLoadReset() {
    formsReset();
}

function formsReset() {
    for (var i = 0; i < document.forms.length; i++) {
        document.forms[i].reset();
    }
}

/*------------------begin main page js --------------------------------*/
function choiceAuto(form){
    var action = form.action;
    var value;    

    value = form.elements["body"].options[form.elements["body"].selectedIndex].value;
    if(value != ""){
        action += "&body=" + value;
    }

    value = form.elements["country"].options[form.elements["country"].selectedIndex].value;
    if(value != ""){
        action += "&" + value + "=all";
    }

    value = form.elements["age"].options[form.elements["age"].selectedIndex].value;
    if("isNew" == value){
        action += "&isNew=true";
    }else if("" != value){
        action += "&year=" + value;
    }

    value = form.elements["minPrice"].value;
    action += "&minPrice=" + value;
    value = form.elements["maxPrice"].value;
    action += "&maxPrice=" + value;

    document.location.href = action;

    return false;
}
/*------------------begin main page js --------------------------------*/

// ----------------------------------------------------------------------------
// HasClassName
//
// Description : returns boolean indicating whether the object has the class name
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function HasClassName(objElement, strClass)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // we found it
            return true;

            }

         }

      }

   // if we got here then the class name is not there
   return false;

   }
//
// HasClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// AddClassName
//
// Description : adds a class to the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function AddClassName(objElement, strClass, blnMayAlreadyExist) //used in catalog.js, suggestUtil.js and this lib
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // if the new class name may already exist in list
      if ( blnMayAlreadyExist )
         {

         // get uppercase class for comparison purposes
         var strClassUpper = strClass.toUpperCase();

         // find all instances and remove them
         for ( var i = 0; i < arrList.length; i++ )
            {

            // if class found
            if ( arrList[i].toUpperCase() == strClassUpper )
               {

               // remove array item
               arrList.splice(i, 1);

               // decrement loop counter as we have adjusted the array's contents
               i--;

               }

            }

         }

      // add the new class to end of list
      arrList[arrList.length] = strClass;

      // add the new class to beginning of list
      //arrList.splice(0, 0, strClass);

      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   else
      {

      // assign modified class name attribute
      objElement.className = strClass;

      }

   }
//
// AddClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// RemoveClassName
//
// Description : removes a class from the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to remove
//
function RemoveClassName(objElement, strClass) //used in catalog.js, suggestUtil.js and this lib
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // remove array item
            arrList.splice(i, 1);

            // decrement loop counter as we have adjusted the array's contents
            i--;

            }

         }

      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   // there is nothing to remove

   }
//
// RemoveClassName
// ----------------------------------------------------------------------------

function toggleFavoriteList(mode){ // used in favoritesBlock.xslt
    var favList = null;
    switch(mode){
    case 'model': favList = document.getElementById('favListModel'); break;
    case 'adv': favList = document.getElementById('favListAdv'); break;
    case 'all':
        var state = document.getElementById('favWidgetState');
        if(!HasClassName(state, 'close')){
            AddClassName(document.getElementById('favListModel').parentNode, 'hide');
            AddClassName(document.getElementById('favListAdv').parentNode, 'hide');
            AddClassName(state, 'close');
        }else{
            RemoveClassName(document.getElementById('favListModel').parentNode, 'hide');
            RemoveClassName(document.getElementById('favListAdv').parentNode, 'hide');
            RemoveClassName(state, 'close');
        }
        break;
    }
    if(favList != null){
        var parentDiv = favList.parentNode;
        if(HasClassName(parentDiv, 'vis')){
            RemoveClassName(parentDiv, 'vis');
            AddClassName(parentDiv, 'close');
            AddClassName(favList, 'hide');
        }else{
            RemoveClassName(parentDiv, 'close');
            AddClassName(parentDiv, 'vis');
            RemoveClassName(favList, 'hide');
        }
    }
}

/*-----------------------------------------------------Url processing-------------------------------------------------*/

function replaceHrefParam(href, paramName, paramValue){
    if(!href.match("([&?])" + paramName + "=")){
        return (href + (href.indexOf("?") == -1 ? "?" : "&") + paramName + "=" + paramValue);

    }else{
        var myRegexp = new RegExp("&*" + '\\b' + paramName + "=[^&]*");
        var repl = (href.indexOf("?") == -1 ? "?" : "&") + paramName + "=" + paramValue;
        return href.replace(myRegexp, repl);
    }
}

function getParameter(name, url) {
	var paramRegexp = new RegExp("[?&]" + name + "=(.[^&]+)");
	if (url.match(paramRegexp)) {
		return RegExp.$1;
	}
}

function removeParameter(url, paramName) {
	var paramRegexp = new RegExp("([?&]" + paramName + "[=].[^&]*)");
	if ( url.match(paramRegexp) ) {
		var param = RegExp.$1;
		return param.indexOf('?') != -1 ? url.replace(param + '&', '?') : url.replace(paramRegexp, '');
	}
	return url;
}

function confirmKeyProccess(event, proccessFunc) {
	var event = event ? event : window.event;
	var keyCode = event.keyCode ? event.keyCode : (event.which ? event.which : null);
	if(keyCode == 0xD){
		proccessFunc.apply(event);
	}
}

function select(element, selectClass) {
	if (element && selectClass) {
		var index = element.className.indexOf(selectClass);
		if (index == -1) {
			element.className += selectClass;
		} else {
			element.className = element.className.substring(0, selectClass);
		}
	}
}

function hide(element) {
	if (element) {
		element.style.display = "none";
	}
}

function show(element) {
	if (element) {
		element.style.display = "";
	}
}

checkUserGeo();
displayCopyToClipboard();
getCheckedCity();