function setUpMenu() {
    var activeItem = $('#nav li.active');

    $('#nav li').bind("mouseover", function() {
        if (activeItem.attr("id") !== $(this).attr("id")) { // check if it is the same
            activeItem.removeClass("hover");
            $(this).addClass("hover");
            $('#nav li.active').removeClass("active").addClass("activeOFF");
            activeItem = $(this);
        }
    });


    $(document.body).bind('mouseover', function() {
        if (activeItem !== undefined) {
            activeItem.removeClass("hover");
            $('#nav li.activeOFF').removeClass("activeOFF").addClass("active");
        }
    });

    $("#nav").bind('mouseover', function() {
        return false;
    });

}

$(document).ready(function() {
    setUpMenu();
});


function setActiveTab(tabId) {
    var tab = $("#" + tabId);
    tab.addClass("active");

    var locat = window.location.href;

    $('#nav li div li a').each(function () {
        if (locat.indexOf(this.href) + 1) {
            this.className = 'active_m';
        }
		if ((this.id != '')&&(locat.indexOf(this.id) + 1))
		{
			this.className = 'active_m';
		}

    });
}

/* popup */
function enlarge()
{
	var popup = document.getElementById('loginpopup');
	popup.style.display = 'block';
}

function hide()
{
	var popup = document.getElementById('loginpopup');
	popup.style.display = 'none';
}

/* tab */
function initTabs()
{
	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{
		if (sets[i].className.indexOf("popular-commented") != -1)
		{
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");
			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					tabs.push(links[j]);
					links[j].tabs = tabs;
					var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

					if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
					else c.style.display = "none";

					links[j].onclick = function ()
					{
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							for (var i = 0; i < this.tabs.length; i++)
							{
								var tab = document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1));
								if (tab)
								{
									tab.style.display = "none";
								}
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							return false;
						}
					}
				}
			}
		}
	}
}
if (window.addEventListener)
	window.addEventListener("load", initTabs, false);
else if (window.attachEvent && !window.opera)
	window.attachEvent("onload", initTabs);

function installPaginator(total, page, path) {
	if (total > 1)
	{
	    $(document).bind('ready', function () {
	    	pag2 = new Paginator('paginator', total, 10, page, path + '&page=');
//	        $('#paginator').paginator({pagesTotal:total, pagesSpan:10, pageCurrent: page, baseUrl:  path + '&page='});
    	});
    }
}

function setUpYandexMapsAPI() {
    var host = document.location.host;
    if (host.indexOf('nur.kz') > 0) {
        // finance.nur.kz
        document.write("<script src='http://api-maps.yandex.ru/1.1/index.xml?key=ADyd30sBAAAAIhpsUAIASiz1Ve6CKMe21OZxia8e8tzB3FoAAAAAAAAAAAC5aawQTRqSUMOwbBcAxQOVwZXqtA=='" +
                       " type='text/javascript'><\/script>");
    } else {
        // prodengi.kz
        document.write("<script src='http://api-maps.yandex.ru/1.1/index.xml?key=AB5oB0sBAAAAkjBgOgIAf0rQXCV_8mSEJapa2xZ1O_NRHWQAAAAAAAAAAADcXwWdf_83Q-DWhd19kn1Hgtk9Rg=='" +
                       " type='text/javascript'><\/script>");
    }
}

function setUpComparator(type, clazz, title) {
    $("#clear").click(function() {
		$('#compare_cnt').html('<img src="/images/status_com.gif" style="display: inline;">');
		$('#compare_cnt2').html('<img src="/images/status_com.gif" style="display: inline;">');
		delete_compare(type, clazz);
    });
    $("#clear2").click(function() {
		$('#compare_cnt').html('<img src="/images/status_com.gif" style="display: inline;">');
		$('#compare_cnt2').html('<img src="/images/status_com.gif" style="display: inline;">');
		delete_compare(type, clazz);
    });
    $("#compare").click(function() {
        window.open('/cat/view_compare/' + type + '/' + clazz, 'Compare','width=1024,height=768,status=no,toolbar=no,menubar=no,resizable=yes,scrollbars=yes,location=yes,top=0,left=0');
    });
    $("#compare2").click(function() {
        window.open('/cat/view_compare/' + type + '/' + clazz, 'Compare','width=1024,height=768,status=no,toolbar=no,menubar=no,resizable=yes,scrollbars=yes,location=yes,top=0,left=0');
    });
}


(function ($) {
    $.fn.selectChain = function (options) {
        var defaults = {
            key: "id",
            value: "label"
        };

        var settings = $.extend({}, defaults, options);

        if (!(settings.target instanceof $)) settings.target = $(settings.target);

        return this.each(function () {
            var $$ = $(this); // combobox

            $$.change(function () {
                var data = null;
                if (typeof settings.data == 'string') {
                    data = settings.data + '&' + this.name + '=' + $$.val();
                } else if (typeof settings.data == 'object') {
                    data = settings.data;
                    data[this.name] = $$.val();
                }

                if (settings.parent != null) {
                    var cl = $("#cityLst option:selected");
                    data['city'] = cl.val();
                }

                settings.target.empty();
                var tmp = document.createElement("OPTION");
                tmp.text = 'загружаю список...';
                settings.target.get(0).options[0] = tmp;
                $.ajax({
                    url: settings.url,
                    data: data,
                    type: (settings.type || 'get'),
                    dataType: 'json',
                    success: function (json) {
                        var options = [], i = 0, o = null;

                        for (i = 0; i < json.length; i++) {
                            // required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
                            o = document.createElement("OPTION");
                            o.value = typeof json[i] == 'object' ? json[i][settings.key] : json[i];
                            o.text = typeof json[i] == 'object' ? json[i][settings.value] : json[i];
                            settings.target.get(0).options[i] = o;
                        }

                        // hand control back to browser for a moment
                        setTimeout(function () {
                            settings.target
                                    .find('option:first')
                                    .attr('selected', 'selected')
                                    .parent('select')
                                    .trigger('change');
                        }, 0);
                    },
                    error: function (xhr, desc, er) {
                        // add whatever debug you want here.
                        //console(xhr, desc, er);
                        alert(xhr + " " + desc + " " + er);
                    }
                });
            });
        });
    };
})(jQuery);


function addCompare(check, id_cat, cat, clazz) {
    var trigger = "/cat/add_compare/" + cat + "/" + clazz + "/" + id_cat;
	$.ajax({
		url: trigger,
		global: false,
		type: "POST",
		dataType: "html",
		success: function(msg){
			check.attr('checked', 'checked');
			$('#compare_cnt').html(msg);
			$('#compare_cnt2').html(msg);
		}
	});



/*    $.post(trigger, {},
           function(data) {
//    check.checked = true;
		check.attr('checked', 'checked');
               $('#compare_cnt').empty().append(data);
           }
            );  */
}

function delCompare(check, id_cat, cat, clazz) {
    var trigger = "/cat/del_compare_id/" + cat + "/" + clazz + "/" + id_cat;
    $.post(trigger, {},
           function(data) {
//    check.checked = false;
		check.removeAttr('checked');
               $('#compare_cnt').empty().append(data);
			   $('#compare_cnt2').empty().append(data);
           });
}

function change_check_table(check, id, cat, clazz, h_chek) {
	$('#compare_cnt').html('<img src="/images/status_com.gif" style="display: inline;">');
	$('#compare_cnt2').html('<img src="/images/status_com.gif" style="display: inline;">');
	if (h_chek.val()==1) {
		check.removeAttr('checked');
		h_chek.val(0);
		delCompare(check, id, cat, clazz);
	}
	else {
		check.attr('checked', 'checked');
		h_chek.val(1);
		addCompare(check, id, cat, clazz);
	}
}

function delete_compare(cat, clazz) {
    $.get('/cat/del_compare_quiet/' + cat + '/' + clazz + '/',
          {},
          function(data) {
              $('#compare_cnt').empty().append(data);
			  $('#compare_cnt2').empty().append(data);
              var field = document.getElementsByName('prd');
              var field_h = document.getElementsByName('prd_h');
              for (i = 0; i < field.length; i++) {
                  field[i].checked = false;
                  field_h[i].value = 0;
              }
          }
            );
}

function update_counter(cat, clazz) {
    $.get('/cat/compare_count/' + cat + '/' + clazz + '/',
          {},
          function(data) {
              $('#compare_cnt').empty().append(data);
			  $('#compare_cnt2').empty().append(data);
          }
            );
}

function showHint(id) {
    document.getElementById('hint_' + id).style.display = 'block';
    return false;
}
function hideHint(id) {
    setTimeout(function() {
        var hint = document.getElementById('hint_' + id);
        hint.style.display = 'none';
    }, 0);
}
/**
 * Get URI parameter by name
 */
function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(string);
        //        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
var amount_temp = '';
/******************************************/

ToggleLinksMenu = function(toogleBlockId, hiddenInputId, options) {
    this.block = document.getElementById(toogleBlockId);
    this.hiddenInput = document.getElementById(hiddenInputId);
    this.options = options;
    this.selected = options.selected;
    this.update();
}

ToggleLinksMenu.prototype =
{
    update: function() {
        this.clear();
        var THIS = this;
        var values = this.options.values;
        var names = this.options.names;
	if (this.block.id == 'currencyList'){
	    var amount_cont = $('form #amount');

	    if (amount_cont.val()!='Пожалуйста, укажите валюту'){
		amount_temp = amount_cont.val();
	    }
	    if(THIS.selected == 0){
		amount_cont.attr('disabled','disabled');
		amount_cont.val('Пожалуйста, укажите валюту');

	    }else{
		amount_cont.removeAttr('disabled');
		amount_cont.val(amount_temp);
	    }
	}
        for (var i = 0; i < values.length; i++) {
            var value = values[i];
            var li = document.createElement('li');
            var link = document.createElement('a');
            link.innerHTML = names[i];
            link.href = "#";
            link.id = "tl_" + value;
            if($("#titles")){
			    switch(THIS.selected){
			     case "1":
			     	var titles="Карточки Visa";
			     break
			     case "2":
			     	var titles="Карточки MasterCard";
			     break
			     case "3":
			     	var titles="Карточки AmericanExpress";
			     break
			     default:
					var titles="Кредитные карты";
				 break
				}
			   $("#titles").html(titles);
		   }
            if (value == THIS.selected) {
                THIS.hiddenInput.value = value;
                li.className = "active";
            } else {
                link.onclick = function() {
                    var val = this.id.substring(3);
                    THIS.selected = val;
                    THIS.hiddenInput.value = val;
                    THIS.update();
                    return false
                };
            }

            li.appendChild(link);
            this.block.appendChild(li);
            this.block.appendChild(document.createTextNode(" "));

        }
    },
    clear: function() {
        while (this.block.firstChild) {
            this.block.removeChild(this.block.firstChild);
        }
    }
}

function setUpCurrencySwitcher(options) {
    $(document).ready(function() {
        new ToggleLinksMenu("currencyList", "currency", options);
    });
	$('#amount').keyup(function(){
		var str = $('#amount').val();
		//str.replace(' ', '');
		var r=/\s+/g;
		str = str.replace(r,'');
		//$('#amount').val(str);
		//alert(str);
		$('#amount').val(str.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 '));
	})
}

function setUpExchangeCurrencyListener() {
    $(document).ready(function() {

        $("#currency_bx").data("current_val", $("#currency_bx option:selected"));

        $('#currency_bx').change(function(data) {
            var icon = $('#currency_icon');
            var current_val = $("#currency_bx option:selected");
            var old_val = $("#currency_bx").data("current_val");
            if (old_val != current_val) {
                var old_cur = old_val.val();
                var new_cur = current_val.val();
                icon.removeClass(old_cur);
                icon.addClass(new_cur);
                $("#currency_bx").data("current_val", current_val);
                $.cookie("last_used_currency", new_cur);
                $('#exchange_form').submit();
            }
        });

    });
}
function setUpExchangeChainListener() {
    $(function () {
        var cityList = $('#cityLst');
        var raionList = $('#raionLst');
        var streetList = $('#streetLst');

        cityList.selectChain({
            target: raionList,
            url: '/obmennik_filter.php',
            data: {ajax: true, action: "city"}
        });

        raionList.selectChain({
            parent: cityList,
            target: streetList,
            url: '/obmennik_filter.php',
            data: {ajax: true, action: "raion"}
        });
    });
    $('#cityLst').trigger('change');
    $('#raionLst').trigger('change');
}

function setUpBankSwitcher() {

    $('#banks').click(function() {
        setTimeout(function() {
            $('#banks').attr('href', '/banknews');
            $('#money').attr('href', 'javascript:void(0);');
            $('#strah').attr('href', 'javascript:void(0);');
            $('#banks').addClass("active");
            $('#money').removeClass("active");
            $('#strah').removeClass("active");
            $('#moneyD').hide();
            $('#strahD').hide();
            $('#banksD').show();
        }, 100);
    });

    $('#money').click(function() {
        setTimeout(function() {
            $('#money').attr('href', '/lenta');
            $('#banks').attr('href', 'javascript:void(0);');
            $('#strah').attr('href', 'javascript:void(0);');
            $('#banks').removeClass("active");
            $('#strah').removeClass("active");
            $('#money').addClass("active");
            $('#banksD').hide();
            $('#strahD').hide();
            $('#moneyD').show();
        }, 100);
    });

    $('#strah').click(function() {
        setTimeout(function() {
            $('#strah').attr('href', '/novosti_o_strakhovanii');
            $('#banks').attr('href', 'javascript:void(0);');
            $('#money').attr('href', 'javascript:void(0);');
            $('#banks').removeClass("active");
            $('#money').removeClass("active");
            $('#strah').addClass("active");
            $('#banksD').hide();
            $('#moneyD').hide();
            $('#strahD').show();
        }, 100);
    });

}

function setUpSubscribeSwitcher() {
    $('#stl').click(function() {
        $('#st').addClass("active");
        $('#mt').removeClass("active");
        $('#stb').show();
        $('#mtb').hide();
    });
    $('#mtl').click(function() {
        $('#mt').addClass("active");
        $('#st').removeClass("active");
        $('#mtb').show();
        $('#stb').hide();
    });
}

function isValidEmail (email, strict)
{
 if ( !strict ) email = email.replace(/^\s+|\s+$/g, '');
 return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
}

function shownurtab ()
{
	var mainm = document.getElementById('nur-main');

	mainm.style.display = 'block';
	mainm.style.zIndex = '101';

}

function CheckAdvForm(frm)
	{
	      if(frm.REVIEW_AUTHOR.value=="") {
			alert("Поле Ваше имя должно быть заполненно!");
			frm.REVIEW_AUTHOR.focus();
			return false;
		  }
      	  if(frm.REVIEW_TEXT.value=="") {
			alert("Поле Сообщение должно быть заполненно !");
			frm.REVIEW_TEXT.focus();
			return false;
		  }
		  if (/*(frm.MAIL_CHEK.checked) && */(frm.REVIEW_MAIL.value=="")){
			alert("Вы не указали email !");
			frm.MAIL_CHEK.focus();
			return false;
		  }
		  if ((frm.MAIL_CHEK.checked) && (!isValidEmail(frm.REVIEW_MAIL.value, true))){
			alert("Email введен не правильно !");
			frm.MAIL_CHEK.focus();
			return false;
		  }

      	  return true;
    	}

function saveFormData(form) {
	if(!form) {
		return false;
	}

	if(!form.id) {
		alert("You should set id attribute in form tag to save or restore it.");
		return false;
	}

	var cookieData = new Array;
	for(var i = 0; i < form.elements.length; i++) {
		var input = form.elements[i];
		if (input.name) {
			var inputName = input.name.replace(/([)\\])/g, "\\$1");

			switch(input.type) {
				case "file": {
					if (input.value == '') input.parentNode.removeChild(input);
					break;
				}
				case "password":

				case "text":
				case "textarea": {
					cookieData.push({type: 'T', name: inputName, value: input.value});
					break;
				}

				case "checkbox":
				case "radio": {
					cookieData.push({type: 'C', name: inputName, value: (input.checked ? 1 : 0)});
					break;
				}

				case "select-multiple":
				case "select-one": {
					cookieData.push({type: 'S', name: inputName, value: input.selectedIndex});
					break;
				}
			}
		}

	}

	var str = "";
	for(var i = 0; i < cookieData.length; i++) {
		var elementData = cookieData[i];
		var value = new String(elementData.value);
		var inputName = new String(elementData.name);

		if(!inputName || !value) {
			continue;
		}

		str += elementData.type + "," + inputName.length + "," + inputName + "," + value.length + "," + value;
	}
	document.cookie="frm" + form.id + "=" + escape(str.replace(/([|\\])/g, "\\$1"));
	return true;
}

function restoreFormData(form) {
	if(!form) {
		return false;
	}

	if(!form.id) {
		alert("You should set id attribute in form tag to save or restore it.");
		return false;
	}
	var cookieName = "frm" + form.id + "=";

	var cookie = new String(unescape(document.cookie));
	var posStart, posEnd;
	if((posStart = cookie.indexOf(cookieName)) == -1) {
		return false;
	}

	if((posEnd = cookie.indexOf(";", posStart)) == -1) {
		posEnd = cookie.length;
	}

	var data = cookie.substring(posStart + cookieName.length, posEnd);
	var pos = 0, cookieData = new Array;

	while(pos < data.length) {
		var inputName;
		var type = data.substring(pos, pos + 1);
		pos += 2;

		var length = parseInt(data.substring(pos, data.indexOf(",", pos)));
		pos = data.indexOf(",", pos) + 1;
		var inputName = data.substring(pos, pos + length);
		pos += length + 1;

		var length = parseInt(data.substring(pos, data.indexOf(",", pos)));
		if(length == 0) {
			pos += 2;
			continue;
		} else {
			pos = data.indexOf(",", pos) + 1;
		}

		var value = data.substring(pos, pos + length);
		pos += length;

		cookieData.push({type: type, name: inputName, value: value});
	}

	for(var i = 0; i < cookieData.length; i++) {
		var elementData = cookieData[i];
		if (elementData.type && elementData.name) {
			switch(elementData.type) {
				case "T": {
					form.elements[elementData.name].value = elementData.value;
					break;
				}

				case "C": {
					form.elements[elementData.name].checked = elementData.value ? true : false;
					break;
				}

				case "S": {
					form.elements[elementData.name].selectedIndex = elementData.value;
					break;
				}
			}
		}
	}
}

$(document).ready(function (){
	$("#top_click_tel a").click(function(){
    	$("#top_tel").show();
	});
	$("#top_tel_close").click(function(){
		$("#top_tel").hide();
	});
});
