var win;
function getRequestObject(url, preload){
	preload = preload || false;
	
	var req = new Ext.data.Connection({url: url});
	if(preload){
		req.on({
  			'beforerequest': function(){ Ext.Msg.wait("Загрузка","Пожалуйста ждите..."); },
  			'requestcomplete': function(){ Ext.Msg.hide(); }
		});
	}
	return req;
}

function showComplects(id, ajax_action, preload, activeTab){
	preload = preload || false;
	activeTab = activeTab || 0;
	var url = 'lib/ajax.php?art_id='+id+'&ajax_action='+ajax_action;
	var req = getRequestObject(url, preload);
	req.request({
  		success: function(response) {
    		Ext.DomHelper.append(document.body, response.responseText);
			showWindow(activeTab);
  		}
	}); 
}

function showWindow(activeTab){
 activeTab = activeTab || 0;
 if(win){
 	win.destroy();
 }
 win = new Ext.Window({
 		applyTo : 'hello-win',
 		layout : 'fit',
 		width : 900,
 		height : 600,
 		closeAction :'hide',
 		//modal:true,
 		autoScroll: true,
 		animScroll: true,
 		enableTabScroll: true,
 		items : new Ext.TabPanel({
 				applyTo : 'hello-tabs',
 				autoTabs : true,
 				activeTab : activeTab,
 				deferredRender: false,
 				enableTabScroll: true,
 				autoScroll: true,
 				closable: true
 				}),
		 buttons: [{
 				text : 'Close',
 				handler : function(){win.hide();}
 				}]
 		
 		});
 
 	win.show();
}

function showArticleImage(path, id, number, ext){
 	document.getElementById("articleImage").innerHTML = "<img src='"+path+id+"_"+number+".jpg' border='1'>";
}

function reloadMiniBasket(){
	var req = new Ext.data.Connection({ url: 'lib/ajax2.php?a=getMiniBasket' });
	req.request({
		success: function(response) {
			var b = document.getElementById('miniBasketId');
			b.innerHTML=response.responseText;
		}
	}); 
}

function handleAddToCart(productId, pricelistId, price, cashless, pricelistName, providerName, deliveryPeriod, quantity, minQuantity){
	if(quantity<minQuantity){
		alert("Минимальный заказ: "+minQuantity+" шт.");
		return;
	}
	var req = new Ext.data.Connection({
		url: 'lib/ajax2.php?a=basketAddProduct&productId='+productId+'&pricelistId='+pricelistId+'&price='+price+'&cashless='+cashless+'&pricelistName='+Url.encode(pricelistName)+'&providerName='+Url.encode(providerName)+'&deliveryPeriod='+deliveryPeriod+'&quantity='+quantity
	});
	req.request({
		success: function(response) { reloadMiniBasket(); }
	}); 
}

function handleBasketEditComment(productId, pricelistId, cashless, comment){
	var req = new Ext.data.Connection({
		url: 'lib/ajax2.php?a=basketEditComment&productId='+productId+'&pricelistId='+pricelistId+'&cashless='+cashless+'&comment='+Url.encode(comment)
	});
	req.request({
		success: function(response) {}
	}); 
}

function editBasketComment(productId, pricelistId, cashless, commentSpanId, currentComment) {
	Ext.MessageBox.show({
		title: 'Комментарий',
		//msg: 'Комментарий:',
        width:300,
        buttons: Ext.MessageBox.OKCANCEL,
        multiline: true,
        value: currentComment,
        fn: function(buttonId, text) {
        	if ( buttonId == 'ok' ) {
        		handleBasketEditComment(productId, pricelistId, cashless, text);
        		document.getElementById(commentSpanId).innerHTML = text;
        	}
        }
    });
}

function handleOrderEditComment(orderItemId, comment){
	var req = new Ext.data.Connection({
		url: 'lib/ajax2.php?a=orderEditComment&orderItemId='+orderItemId+'&comment='+comment
	});
	req.request({
		success: function(response) {}
	}); 
}

function editOrderComment(orderItemId, commentSpanId, currentComment) {
	Ext.MessageBox.show({
		title: 'Комментарий',
		//msg: '',
        width:300,
        buttons: Ext.MessageBox.OKCANCEL,
        multiline: true,
        value: currentComment,
        fn: function(buttonId, text) {
        	if ( buttonId == 'ok' ) {
        		handleOrderEditComment(orderItemId, text);
        		document.getElementById(commentSpanId).innerHTML = text;
        	}
        }
    });
}

function showInfo(memoInfo) {
	Ext.MessageBox.alert('info', memoInfo, null);
}

function setCookie(strCookie,strValue){
	document.cookie=strCookie + "=" + strValue + ";expires=Fri, 31 Dec 2070 23:59:59 GMT;";
}

function ask(txt) {
	Ext.MessageBox.confirm(
		'Confirm', txt, 
		function(btn){
			if ( btn == 'yes' ) {
				return true;
			}
		}
	);
	return false;
}

function deleteOrderItem(orderItemId, txt) {
	if(confirm('Вы действительно хотите удалить '+txt+"?")) {
		postToURL(window.location, {'action':'deleteOrderItem', 'oiid':orderItemId});
	}
}

function postToURL(url, values){
    values = values || {};

    var form = createElement("form", {action: url, method: "POST", style: "display: none"});
    for (var property in values) {
        if (values.hasOwnProperty(property)) {
            var value = values[property];
            if (value instanceof Array) {
                for (var i = 0, l = value.length; i < l; i++){
                    form.appendChild(createElement("input", {type: "hidden", name: property, value: value[i]}));
                }
            }
            else {
                form.appendChild(createElement("input", {type: "hidden", name: property, value: value}));
            }
        }
    }
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

var createElement = (function(){
    // Detect IE using conditional compilation
    if (/*@cc_on @*//*@if (@_win32)!/*@end @*/false){
        // Translations for attribute names which IE would otherwise choke on
        var attrTranslations = {"class": "className", "for": "htmlFor" };

        var setAttribute = function(element, attr, value){
            if (attrTranslations.hasOwnProperty(attr)){
                element[attrTranslations[attr]] = value;
            }
            else if (attr == "style"){
                element.style.cssText = value;
            }
            else{
                element.setAttribute(attr, value);
            }
        };

        return function(tagName, attributes){
            attributes = attributes || {};

            // See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs
            if (attributes.hasOwnProperty("name") ||
                attributes.hasOwnProperty("checked") ||
                attributes.hasOwnProperty("multiple"))
            {
                var tagParts = ["<" + tagName];
                if (attributes.hasOwnProperty("name")){
                    tagParts[tagParts.length] =
                        ' name="' + attributes.name + '"';
                    delete attributes.name;
                }
                if (attributes.hasOwnProperty("checked") &&
                    "" + attributes.checked == "true"){
                    tagParts[tagParts.length] = " checked";
                    delete attributes.checked;
                }
                if (attributes.hasOwnProperty("multiple") &&
                    "" + attributes.multiple == "true"){
                    tagParts[tagParts.length] = " multiple";
                    delete attributes.multiple;
                }
                tagParts[tagParts.length] = ">";

                var element = document.createElement(tagParts.join(""));
            }
            else{
                var element = document.createElement(tagName);
            }

            for (var attr in attributes){
                if (attributes.hasOwnProperty(attr)){
                    setAttribute(element, attr, attributes[attr]);
                }
            }

            return element;
        };
    }
    // All other browsers
    else{
        return function(tagName, attributes){
            attributes = attributes || {};
            var element = document.createElement(tagName);
            for (var attr in attributes){
                if (attributes.hasOwnProperty(attr)){
                    element.setAttribute(attr, attributes[attr]);
                }
            }
            return element;
        };
    }
})();

function getTableContent(id){
	var table = document.getElementById(id);
	var res='';
	for(var r=1; r<table.rows.length-1; r++){
		var row=table.rows[r];
		for(var col=0; col<row.cells.length; col++){
			var cell=row.cells[col].innerHTML.trim().toLowerCase();
			if(cell.indexOf("<input")==0){
				var p1=cell.indexOf("value");
				var p2=cell.indexOf(" ", p1);
				cell=cell.substr(p1+6, p2-p1-6).trim();
			}
			if(cell.indexOf("<select")==0){
				var p1=cell.indexOf("selected>");
				var p2=cell.indexOf("<", p1);
				cell=cell.substr(p1+9, p2-p1-9).trim();
			}
			if(cell.indexOf("<")==0){
				cell='';
			}
			res += cell+'\t';
		}
		res += '\r\n';
	}
	return res;
}

function copyToClipboard(id) {
	//alert(getTableContent(id));
	if(window.clipboardData && clipboardData.setData ){
		clipboardData.setData("Text", getTableContent(id));
		alert("Скопировано");
	} else {
		alert("Не поддерживается в данном браузере");
	}
}
function pageHeight() {
	return  window.innerHeight != null? window.innerHeight-20 : document.documentElement && document.documentElement.clientHeight ?
		document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}
function load(isAdmin) {
//	document.getElementById('leftMenu').style.height = (pageHeight()-50) + "px";
	//s=window.location.toString();
	if(/*s.indexOf("query")>0 && */!isAdmin)
		reloadMiniBasket();
}

function showHistory(){
	historyWindow = new Ext.Window({
		title: 'Вы искали:',
 		width : 300,
 		height_ : 200,
 		closeAction :'hide',
 		autoScroll_: true,
 		animScroll_: true,
 		html: historyHtml,
 		buttons: [{
			text : 'Close',
			handler : function(){historyWindow.hide();}
			}]
		});
	historyWindow.show();
	return false;
}


var Url = {
		 
		// public method for url encoding
		encode : function (string) {
			return escape(this._utf8_encode(string));
	//return this._utf8_encode(string);
	//return escape(string);
		},
	 
		// public method for url decoding
		decode : function (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;
		}
	 
	}
