function engine(mode,params) {
    switch (mode) {
        case "List": ListItems(params);
             break
        case "Edit": EditItem(params);
             break
        case "FormSave": FormSave(params);
             break
        case "DeleteItem": DeleteItem(params);
             break
        case "LevelUp": LevelUp(params);
             break
        case "LevelDn": LevelDn(params);
             break
        case "DeleteImg": DeleteImg(params);
             break
        case "ShowFormAfterEdit": ShowFormAfterEdit(params);
             break
        case "Compare": CompareGoods();
             break             
        case "CatsField": CatsField(mode,param,id);
             break
        case "Show": PostToEngine(mode,params);
             break	
        case "GetPage": PostToEngine(mode,params);
             break				 
    }
}

	function MV_Delete(id,i) {
		$('#dpe_mv_'+id+'-'+i).remove();
		MV_Update_All(id);
	}
	
	function MV_Add(id) {
		var res=$('#dpe_mvf_'+id+' .dpe_mv_empty').html();
		$('#dpe_mv_'+id).append(res);
		var num=Number($('#dpe_mv_count_'+id).val())+1;
		var dpe_mv_id='dpe_mv_'+id+'-'+num;
		$('#dpe_mv_count_'+id).val(num);
		$('#dpe_mv_'+id+' li[id=new]').attr('id',dpe_mv_id);
		$('#'+dpe_mv_id+' .ui-icon-scissors').attr('onclick','MV_Delete(\"'+id+'\",\"'+num+'\");');
		$('#'+dpe_mv_id+' input').each(function(i) {
			$(this).attr('id',$(this).attr('id')+num);
			$(this).attr('name',$(this).attr('name')+num);
		});
	}
	
	function MV_Update_All(id) {
		$('#dpe_mvh_'+id+' li:first input:hidden').each(function(i) {
			MV_Update_Field(id,$(this).attr('id'));
		});
	}

	function MV_Update_Field(id,name) {
		var res='';
		$('#dpe_mv_'+id+' li:visible input[rel='+name+']').each(function(i) {
			if (res>'') {res+='|';}
			res+=$(this).val();
		});
		$('#dpe_mvh_'+id+' #'+name).val(res);
	}



    function AutoCompleteField(name) {
		$("#"+name ).autocomplete({
			source: "/engine/autocomplete.php?name="+name
		});

    }

function Alert(msg) {
    if ($('#dpe_Alert').length) {$('#dpe_Alert').remove();}
    $("body").append("<div id='dpe_Alert'><div style='padding: 20px;' class='ui-state-error ui-corner-all'><p><span style='float: left; margin-right: 0.3em;' class='ui-icon ui-icon-alert'></span>"+msg+"</p></div></div>");
    $("#dpe_Alert").dialog({
        title: 'Внимание!',
        modal: true, closeOnEscape:true, stack:true, zindex:1000,
        close: function(method, ui) {$('#dpe_Alert').remove();},
        buttons: {'OK': function() {$('#dpe_Alert').remove();}}
    });
}

function CompareGoods() {
    if ($("#Compare").length) {} else {
    $("#content").append("<div id='Compare'></div>");
    $("#Compare").dialog({
        title: 'Сравнение товаров',
        modal: true, closeOnEscape:true, stack:true, zindex:100,
        width: $(window).width()-10,
        height: $(window).height()-10,
        close: function(method, ui) {$('#Compare').remove();},
        buttons: {'OK': function() {$('#Compare').remove();}}
    });        
    }
    $.get("/engine/engine.php?mode=Compare", function(data){
        $("#Compare").html(data);
    });    
    
}

function CatsField(mode,params,jid) {
    var id=mode;
    var page="/engine/engine.php?mode="+mode+"&"+params;
    $.get(page, function(data){
        $(jid).html(data);
    });    
}

function PostToEngine(mode,params) {
    var id=mode; var jid=PrepareId(mode);
    var page="/engine/engine.php?mode="+mode+"&"+params;
    $.get(page, function(data){
        $("#content").html(data);
    });    
}


function CreateTmpVar(id) {
var jid="#"+id;
if ($(jid).lenght) {$(jid).remove();}
$("<input type=hidden id='"+id+"' />").appendTo("body");
return jid;
}

function DeleteImg(params) {
    var id="DeleteImg"; var jid=PrepareId(id);
    var page="/engine/engine.php?mode="+id+"&"+params;
    $.get(page, function(data){
        if (data>" ") {alert(data);}
    });    
}

function DeleteItem(params) {
    var id="DeleteItem"; var jid=PrepareId(id);
    var page="/engine/engine.php?mode="+id+"&"+params;
    $.get(page, function(data){
        //if (data>" ") {alert(data);}
        engine("PageList","");
    });    
}

function ListItems(params) {
    var id="List"; var jid=PrepareId(id);
    var page="/engine/engine.php?mode="+id+"&"+params;
    $.get(page, function(data){
        $("#content").html(data);
        $("title").html($("#content"+" h1").html());
    });
}

function EditItem(params) {
    var id="Edit"; var jid=PrepareId(id);
    var page="/engine/engine.php?mode="+id+"&"+params;
    $.post(page, function(data){
    $(jid).html(data);
    });
}

function DialogClose(obj) {
    $(obj).dialog("close");
}

function FormSave(params) {
        //SpawEngine.updateFields();
        var params=$("form").serialize();
        var page="/engine/engine.php?mode=FormSave";
        $.post(page, params, function(data){
        //if (data=="") {} else {alert(data);}
        });
}

function Form2script(page) {
        var params=$("form").serialize();
        $.post(page, params, function(data){
          if (data=="") {} else {Alert(data);}
        });
}

function ShowFormAfterEdit(params) {
    var page="/engine/engine.php?mode=Show"+params;
    $.post(page, params, function(data){  
    $("#content").html(data);
    });
}

function PrepareId(id) {
var jid="#"+id;
if ($(jid).lenght) {$(jid).remove();}
$("<div id='"+id+"'></div>").appendTo("body");
return jid;
}

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 setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function GetPages() {

var itemname=$("#dpe_id").val();
var formname=$("#dpe_form").val();
if (formname=='Cats') {formname+="&Name="+$("#Name").val();}
if ($("#dpe_edit h1").length) {$("#dpe_edit h1").hide();}
    if ($("#dpe_edit").length) {
        $("#dpe_edit").dialog({
            modal: true, 
            width: $("#content").width(),
            close: function(event, ui) {$(this).remove();},
			beforeClose: function(event, ui) {ReturnToPrev();},
            title: $("#dpe_edit h1").html(),
buttons: {   "Удалить": function() {
                    if (confirm('Удалить запись?')) {engine('DeleteItem','id='+itemname); $(this).remove(); ContentLoader(); engine('List','&form='+formname)};
            },
	         "Не сохранять": function() {
			 		if ($('#ReturnMode').length) {ReturnToPrev();}
                	$(this).remove();
            },
	         "Сохранить": function() {
	               engine("FormSave","");
                   ReturnToPrev();
				   $(this).remove();

            }
	   }
       
});

    }    

function ReturnToPrev() {
	if ($('#ReturnMode').length) {
		var mode=$('#ReturnMode').val();
		var param="";
		if ($('#ReturnForm').length) {param=param+'&form='+$('#ReturnForm').val();}
		if ($('#ReturnId').length) {param=param+'&id='+$('#ReturnId').val();}
	   	engine(mode,param)
	} else {
		$(this).remove();
		ContentLoader();
		engine('List','&form='+formname)				   	
	}	
}


}

//=========================================
function ShowThumbs(id) {
//=========================================
var dsc=$("#ImagesDescr").val(); 
var img=$("#Images").val();
var arr=explode("|",img); var drr=explode("|",dsc);
var out="";
for (i=0; i<arr.length; i++) { 
	if (isNaN(arr[i])) {drr[i]="";}
	if (arr[i]!="")	{
        out+="<li  class='ui-state-default'>";
		out+="<img src='/tn-"+arr[i]+"' value='"+arr[i]+"' title='"+drr[i]+"' />";
		out+="<span style='position:absolute;margin-top:-25px;margin-left:85px;z-index:100;' onclick=\"ShowThumbsDel('"+id+"','"+arr[i]+"');\" class='ui-icon ui-icon-trash'></span>";
        out+="</li>";
	}
}
$("#"+id).html(out);
}

function ShowThumbsAfter(id) {
	var img="";
	var dsc="";
	$("#"+id+" li img").each(function(i) {
		if (img>"") {img+="|"; dsc+="|";}
		img+=$(this).attr("value");
		dsc+=$(this).attr("title");
	});
	$("#Images").val(img);
	$("#ImagesDescr").val(dsc);
}


//=========================================
function ShowThumbsDel(id,img) {
//=========================================
if (confirm('Удалить изображение?')) {
    $("#"+id+" li img[value='"+img+"']").parent('li').remove();
	ShowThumbsAfter(id);
	ShowThumbs(id);
}
}

//=========================================
function Add2Basket(str,quant) {
//=========================================
var quant=Number(quant);
if (getCookie("basket")==null) {var basket=Array();} else {var basket=explode("|",getCookie("basket"));}
if (getCookie("quants")==null) {var quants=Array();} else {var quants=explode("|",getCookie("quants"));}
var key=false;
var len=count(basket);
for (var i = 0; i < len; i++) {
    if (basket[i]==str) {quants[i]=Number(quants[i])+quant; key=true;}
}
if (key==false) {basket[len]=str; quants[len]=quant;}
setCookie("basket",implode("|",basket));
setCookie("quants",implode("|",quants));
}

//=========================================
function Add2Compare(id) {
//=========================================
if (getCookie("compare")==null) {var compare=";";} else {var compare=getCookie("compare");}
var compare=explode(";",compare);
var key=false;
var len=count(compare);
for (var i = 0; i < len; i++) {   if (compare[i]==id) {key=true;}   }
if (key==false) {compare[len]=id;}
var compare=implode(";",compare);
if (len>0) {len=len-1;}
Alert("Товар добавлен в сравнение.<br />Всего товаров в сравнении: "+len);
$("#dpe_Alert").dialog({
    buttons: {'Сравнить': function() {$('#dpe_Alert').remove();engine('Compare','');},
              'Закрыть': function() {$('#dpe_Alert').remove();}}
    });
setCookie("compare",compare);
}

//=================================
function CheckOrder() {
//=================================
var quant=1;
var res=true;
if ($("#size").length) {
    if ($("#size").val()=='') {Alert("Выберите размер"); var res=false;} 
}
if ($("#color").length) {
    if ($("#color").val()=='') {Alert("Выберите цвет"); var res=false;} 
} 


if (res==true) {
	var arr = Array($("#id").val(),$("#size").val());
	var str=implode('_',arr);
	Add2Basket(str,quant);
	BasketInfo(); 
}
return res;
}

function BasketInfo() {
   $.get("/_basketinfo.htm", function(data){
        if ($('#BasketInfo').length) {$('#BasketInfo').remove();}
        $("#content").append("<div id=BasketInfo></div>");
		$("#BasketInfo").html(data).dialog({
		    buttons: {'Оформить заказ': function() {document.location.href="basket.htm"},
					  'Перейти в каталог': function() {
					  		$('#BasketInfo').remove();
							ContentLoader();
							engine('GetPage','PageName=catalog');
							},
             		  'Закрыть': function() {$('#BasketInfo').remove();}}
		});
		
   });
  
}

function ClearBasket() {
    setCookie("basket",""); 
	setCookie("quants","");  
	$("#BasketTable").html("<h1>Ваша корзина пуста!</h1>");  
}

function BasketRecalc() {
	var qnt=0; var sum=0;
	$("#BasketTable input[name^='qnt_']").each(function() {
		if ($(this).attr('name')=="qnt_total") {} else {qnt+=Number($(this).val());}
	});
	$("#BasketTable input[name^='sum_']").each(function(i) {
		if ($(this).attr('name')=="sum_total") {} else {
			var key=explode("_",$(this).attr('name'));
			$(this).val($('#price_'+key[1]).val()*$('#qnt_'+key[1]).val());
			sum+=Number($(this).val());
		}
	});

	$("#qnt_total").val(qnt);
	$("#sum_total").val(sum);
}

function BasketSend() {
	    $("#SendButton").remove();
		var params=$("#BasketForm form").serialize();
        var page="_basket.htm";
        $.post(page, params, function(data){
        	Alert(data);
        });
		return false;
}

function ContentLoader() {
    $("#content").html("<div style='width:100%; height:200px; text-align:center;'><br /><br /><br /><br /><br /><img src='engine/images/ajax-loader.gif'></div>");
}

function ShowNews(id) {
    var jid="#news_"+id;
    if ($(jid).lenght) {$(jid).remove();}
    $("<div id='news_"+id+"'></div>").appendTo("#content");
    var page="/news.php?&mode=ShowNews&id="+id;
    $.get(page, function(data){
    $(jid).html(data);
    $(jid).dialog({
        modal: true, height:500, width:800,  closeOnEscape:true, stack:false, zindex:0,
        title: $(jid+" h1").html()
        });
    });
}


