var show_e;
var show_img;

var flag=0;

/*------------------------------------------*/

$(function() {
   window.CATALOG_SEARCH = is_catalog_search();

   $("#countform select").change(function() {
        if (CATALOG_SEARCH) {
            $("#countform").attr("action", "");
        }
        $("#countform").submit();
    });

    //if (CATALOG_SEARCH) {
        $("a.sort-by-price").bind("click", {by: "dcost"}, sort_handler);
        $("a.sort-by-name").bind("click", {by: "name"}, sort_handler);
    //}

    $("#searchform input[name='findtext']").keydown(function(e) {
        if (e.keyCode == 13) {
            $("#search-button").triggerHandler("click");
            return false;
        }
    });

    $("#search-button").click(function() {
       var form = $("#searchform");
       var findtext = $("input[name='findtext']", form).val();
       findtext = translateStr(findtext);
       //alert(findtext);
       form.attr("action", "/catalog/" + findtext + "/");
       form.submit();
       return false;
    });

    $("#first-letter-search a").click(function () {
        var letter = $(this).text();
        letter = letter.toLowerCase();
        letter = translateStr(letter);
        window.location = "/catalog/starts-with/" + letter + "/";
        return false;
    });
});

function sort_handler (e) {
    var by = e.data.by;
    var form = $("#sort-by-form");
    $("input[name='sort']", form).val(by);
    form.submit();
    return false;
}

function is_catalog_search() {
    var loc = window.location;
    loc= loc + "";
    var a = loc.split("/");
    if (a[3] == "catalog") {
        return true;
    }
    return false;
}

mapEn = "je|yii|ji|yo|ya|shc|sh|ea|ii|zh|ch|iy|ts|u|w|v|i|y|d|t|b|p|n|f|'|'|z|l|k|s|m|r|s|h|j|g|_|a|o|-|e|_".split('|');

mapRu = "э|ы|й|ё|я|щ|ш|я|й|ж|ч|ю|ц|у|в|в|и|у|д|т|б|п|н|ф|ь|ъ|з|л|к|с|м|р|с|х|ж|г|_|а|о|-|е| ".split('|');

function translateStr(str){

    /*
    for(i = 0; i < mapEn.length; ++i) 
        while (s.indexOf(mapEn[i]) >= 0)
            s = s.replace(mapEn[i], mapRu[i]); 
    */ 
    var enStr = '';

    for (i=0;i<=str.length-1;i++) {
        //var char = str[i];
        var char = str.substr(i, 1);
        var index = $.inArray(char, mapRu);
        if (index != -1) {
            enStr += mapEn[index];
        } else {
            enStr += char;
        }
    }
		
		enStr=enStr.toLowerCase();
		
    return enStr;
}
/*------------------------------------------*/


function setSelect(name, value) {
	e = document.getElementById(name);
	for(var i=0;i<e.length;i++) {
		if(e.options[i].value==value) e.selectedIndex = i;
	}
}

function showwin(x,y,nam) {
	if (flag == 1) {
		sw.close()
		flag=0
	}

	x = x + 20;
	y = y + 20;

	
	eval("sw=window.open(Name=\""+nam+"\",\"Изображение\",\"top=20,left=220,width="+x+",height="+y+",scrollbars=no,resizable=no\")")

	sw.focus()
	flag = 1
}

function showfoto(x, y, url) {
	if (flag == 1) {
		sw.close()
		flag=0
	}

	//x = x + 20;
	//y = y + 20;

	
	eval("sw=window.open('','Изображение','top=20,left=220,width='+x+',height='+y+',scrollbars=no,resizable=no')");

	sw.document.write("<html><head><title>Изображение");
	sw.document.write("</title></head><body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>");
	sw.document.write("<center><table width='100%' height='100%' cellspacing=0 cellpadding=0 border=0><tr><td align=center>");
	sw.document.write("<img border='0' src='"+url+"'>");
	sw.document.write("</td></tr></table>");
	sw.document.write("</center>");
	sw.document.write("</body></html>");

	
	sw.focus()
	flag = 1
}

function showflash(page,x,y)
{
	eval("sf=window.open(Name=\""+page+"\",\"FLASH\",\"top=20,left=220,width="+x+",height="+y+",scrollbars=no,resizable=no\")")
}

function domenu(id,e,img) { 
	if(id == pageid) {
		e = document.getElementById(e);
		img = document.getElementById(img);
		if(e&&img) {
			//show(e,img);
			show_e = e;
			show_img = img;
		} else alert("Ошибка");
	}
	return 0;
}

function showmenu() {
	if(show_e && show_img) show(show_e, show_img);
}

function catalog_bask(zena,count) {
	if(document.getElementById('catalog_count')) catalog_count.innerText = count;
	if(document.getElementById('catalog_zena')) catalog_zena.innerText = zena;
}

var ArrayBaskId = new Array();

function parce_baskinfo() {
	var s = document.getElementById('baskinfo').innerHTML;
	listID = s.split(';');
	for (var i = 0; i < listID.length; i++) {
		if(listID[i] != "") {
			m = listID[i].split(':');
			ArrayBaskId[m[0]] = m[1];
		}
	}
}

function catalog_check(id,e) {
	if(ArrayBaskId[id]!=null) {
		e = document.getElementById(e);
		/*if(e) e.checked = "true";
		else e.checked = "false";*/
		if(e) e.value = ArrayBaskId[id];
	}
}

function catalog_buy(cost,id,e) {
	e = document.getElementById(e);
	//ordertype = document.getElementById(ordertype);

	if(e==null) alert("Ошибка скрипта");
		
	//check = e.checked;
	colbuy = e.value;
	if(colbuy=="") colbuy = 0;
	
	location.href='/?ext=buy&id=' + id + '&colbuy=' + colbuy;
	return;
	
	if(window.showModalDialog==null) {
		location.href='./?act=buy&page=' + id + '&colbuy=' + colbuy;
		return;
	}
	
	/*if(document.frames('doframe')) document.frames('doframe').location.href='./?act=buy&frame=1&id=' + id;
	else location.href='./?act=buy&id=' + id;*/
	
	if(document.getElementById('catalog_count')) count = catalog_count.innerText;
	if(document.getElementById('catalog_zena')) oldzena = catalog_zena.innerText;
	
	if(zena==null) zena = 0;
	if(count==null) count = 0;
	
	oldcol = 0;
	if((ArrayBaskId[id]!=null)&&(ArrayBaskId[id]!=0)) {
		oldcol = ArrayBaskId[id];
		if(colbuy==0) {
			count--;
		}
	} else {
		if(colbuy>0) count++;
	}
	ArrayBaskId[id] = colbuy;
	
	cost = parseInt(zena) * colbuy + parseInt(oldzena) - parseInt(zena) * oldcol;
	
	catalog_bask(cost,count);

	window.showModalDialog('./?act=buy&frame=1&page=' + id + '&colbuy=' + colbuy, '', 'menubar=no,directories=no,location=no,toolbar=no,scrollbars=no,status=no,resizable=no,height=15,width=350,dialogWidth:350px; dialogHeight:15px');
}

function catalog_col_keypres(id,onewcol,zena,ocol,ordertype) {
	if(event.keyCode==13) catalog_modify(id,onewcol,zena,ocol,ordertype);
	if((event.keyCode<48)||(event.keyCode>57)) event.keyCode = 0;
}

function catalog_newcol_keypres(zena,id,text_buy,ordertype) {
	if(event.keyCode==13) catalog_buy(zena,id,text_buy,ordertype);
	if((event.keyCode<48)||(event.keyCode>57)) event.keyCode = 0;
}

function catalog_modify(id,onewcol,zena,ocol,ordertype) {
	onewcol = document.getElementById(onewcol);
	ocol = document.getElementById(ocol);
	ordertype = document.getElementById(ordertype);
	
	if((onewcol==null)||(ocol==null)||(ordertype==null)) alert('Ошибка определения ID. \n Ваш браузер не поддрердивает JavaScript');
	
	if(ordertype.checked) ot = 1;
	else ot = 0;

	newcol = onewcol.value;
	if(newcol=="") newcol = 0;
	oldcol = ocol.value;
	ocol.value = newcol;
	
	/*var sum = document.all.catalog_sum.innerText;
	var nalcurs = document.all.catalog_nalcurs.innerText;
	var beznalcurs = document.all.catalog_beznalcurs.innerText;
	var nalitogo = document.all.catalog_nalitogo.innerText;
	var beznalitogo = document.all.catalog_beznalitogo.innerText;
	
	sum = parseInt(sum,10) + zena*(newcol-oldcol);
	nalitogo = parseInt(nalitogo,10) + zena*(newcol-oldcol)*nalcurs;
	beznalitogo = parseInt(beznalitogo,10) + zena*(newcol-oldcol)*beznalcurs;
	
	document.all.catalog_sum.innerText = sum;
	document.all.catalog_nalitogo.innerText = nalitogo;
	document.all.catalog_beznalitogo.innerText = beznalitogo;
	
	onewcol.select();
	
	if(document.all.doframe) document.all.doframe.src='./?act=modify&fast=1&id=' + id + '&center=buy&newcol='+newcol;
	else location.href='./?act=modify&id=' + id + '&center=buy&newcol='+newcol;*/
	
	location.href='./?act=modify&id=' + id + '&center=buy&newcol='+newcol+'&ordertype='+ot;
}

// Создание массива для хранения ссылок на дочерние окна. 
/* Каждый член данного массива будет окном объекта, созданного
ниже с использованием метода createWindow. */
var windows = new Array();

function newWindow(url, wname) {
// Конструктор для окна
/* Данная функция может быть вызвана только функцией
   createWindow, которая приведена ниже. */
var features = "";
if (null != arguments[2])
   features = arguments[2];
return window.open(url, wname, features);
}

function createWindow(url, wname) {
// Добавление окна в семейство окон.
var features = arguments[2] == null ? "" : arguments[2];
windows[wname] = new newWindow(url, wname, features);
}

function closeWindows() {
// Закрытие всех окон, открытых методом addWindow. 
/* Для закрытия окна вызывается его метод close. */ 
/* Данная функция может быть вызвана в ходе события onunload
   для автоматического закрытия всех открытых окон.  */
for (w in windows)
   if (!windows[w].closed)
	  windows[w].close();
}

window.onunload=closeWindows;