
Ext.lib.Ajax.isCrossDomain = function(u) {
	var match = /(?:(\w*:)\/\/)?([\w\.]*(?::\d*)?)/.exec(u);
	if (!match[1]) return false; // No protocol, not cross-domain
	return (match[1] != location.protocol) || (match[2] != location.host);
};

Ext.override(Ext.data.Connection, {

    request : function(o){
        if(this.fireEvent("beforerequest", this, o) !== false){
            var p = o.params;

            if(typeof p == "function"){
                p = p.call(o.scope||window, o);
            }
            if(typeof p == "object"){
                p = Ext.urlEncode(p);
            }
            if(this.extraParams){
                var extras = Ext.urlEncode(this.extraParams);
                p = p ? (p + '&' + extras) : extras;
            }

            var url = o.url || this.url;
            if(typeof url == 'function'){
                url = url.call(o.scope||window, o);
            }

            if(o.form){
                var form = Ext.getDom(o.form);
                url = url || form.action;

                var enctype = form.getAttribute("enctype");
                if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
                    return this.doFormUpload(o, p, url);
                }
                var f = Ext.lib.Ajax.serializeForm(form);
                p = p ? (p + '&' + f) : f;
            }

            var hs = o.headers;
            if(this.defaultHeaders){
                hs = Ext.apply(hs || {}, this.defaultHeaders);
                if(!o.headers){
                    o.headers = hs;
                }
            }

            var cb = {
                success: this.handleResponse,
                failure: this.handleFailure,
                scope: this,
                argument: {options: o},
                timeout : this.timeout
            };

            var method = o.method||this.method||(p ? "POST" : "GET");

            if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
                url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
            }

            if(typeof o.autoAbort == 'boolean'){ // options gets top priority
                if(o.autoAbort){
                    this.abort();
                }
            }else if(this.autoAbort !== false){
                this.abort();
            }
            if((method == 'GET' && p) || o.xmlData || o.jsonData){
                url += (url.indexOf('?') != -1 ? '&' : '?') + p;
                p = '';
            }
            if (o.scriptTag || this.scriptTag || Ext.lib.Ajax.isCrossDomain(url)) {
               this.transId = this.scriptRequest(method, url, cb, p, o);
            } else {
               this.transId = Ext.lib.Ajax.request(method, url, cb, p, o);
            }
            return this.transId;
        }else{
            Ext.callback(o.callback, o.scope, [o, null, null]);
            return null;
        }
    },
    
    scriptRequest : function(method, url, cb, data, options) {
        var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;
        var trans = {
            id : transId,
            cb : options.callbackName || "stcCallback"+transId,
            scriptId : "stcScript"+transId,
            options : options
        };

        url += (url.indexOf("?") != -1 ? "&" : "?") + data + String.format("&{0}={1}", options.callbackParam || this.callbackParam || 'callback', trans.cb);

        var conn = this;
        window[trans.cb] = function(o){
            conn.handleScriptResponse(o, trans);
        };

//      Set up the timeout handler
        trans.timeoutId = this.handleScriptFailure.defer(cb.timeout, this, [trans]);

        var script = document.createElement("script");
        script.setAttribute("src", url);
        script.setAttribute("type", "text/javascript");
        script.setAttribute("id", trans.scriptId);
        document.getElementsByTagName("head")[0].appendChild(script);

        return trans;
    },

    handleScriptResponse : function(o, trans){
        this.transId = false;
        this.destroyScriptTrans(trans, true);
        var options = trans.options;
        
//      Attempt to parse a string parameter as XML.
        var doc;
        if (typeof o == 'string') {
            if (window.ActiveXObject) {
                doc = new ActiveXObject("Microsoft.XMLDOM");
                doc.async = "false";
                doc.loadXML(o);
            } else {
                doc = new DOMParser().parseFromString(o,"text/xml");
            }
        }

//      Create the bogus XHR
        response = {
            responseObject: o,
            responseText: (typeof o == "object") ? Ext.util.JSON.encode(o) : String(o),
            responseXML: doc,
            argument: options.argument
        }
        this.fireEvent("requestcomplete", this, response, options);
        Ext.callback(options.success, options.scope, [response, options]);
        Ext.callback(options.callback, options.scope, [options, true, response]);
    },
    
    handleScriptFailure: function(trans) {
        this.transId = false;
        this.destroyScriptTrans(trans, false);
        var options = trans.options;
        response = {
            argument:  options.argument,
            status: 500,
            statusText: 'Server failed to respond',
            responseText: ''
        };
        this.fireEvent("requestexception", this, response, options, {
            status: -1,
            statusText: 'communication failure'
        });
        Ext.callback(options.failure, options.scope, [response, options]);
        Ext.callback(options.callback, options.scope, [options, false, response]);
    },
    
    // private
    destroyScriptTrans : function(trans, isLoaded){
        document.getElementsByTagName("head")[0].removeChild(document.getElementById(trans.scriptId));
        clearTimeout(trans.timeoutId);
        if(isLoaded){
            window[trans.cb] = undefined;
            try{
                delete window[trans.cb];
            }catch(e){}
        }else{
            // if hasn't been loaded, wait for load to remove it to prevent script error
            window[trans.cb] = function(){
                window[trans.cb] = undefined;
                try{
                    delete window[trans.cb];
                }catch(e){}
            };
        }
    }
});

function allst(iditem, kol)
{

	//alert(iditem);
	Ext.Ajax.request({
		// waitMsg: 'Подождите пожалуйста...',
		url: '/index.php',
		method: 'GET',
		params: {
			task: "additem",
			item: iditem,
			kol: kol
		},
		success: function(o){

			var a = Ext.decode(o.responseText);
			var items = a.items;
			var prices = a.price;
			Ext.get('allprice').update(prices);
			Ext.get('allitem').update(items);


			var ww =  new Ext.Window({
				html: '<center><b><font size="3" >Товар добавлен в корзину',
				buttonAlign: 'center',
				width: '300',
				buttons: [{
					text: 'Продолжить покупки',
					handler: function()
					{
						ww.hide();
					}
				},
				{
					text: 'Перейти в корзину',
					href: '/cart/',
					target: "_self",
					handler: function() {
						location.href = '/cart/';
						ww.hide();
					}
				}
				]
			});
			ww.show();



		}
	});

};

function redit(data)
{
alert(22);
//window.open(data, '_SELF');
}
function ShopImage(data){
	Ext.DomHelper.overwrite('images', {
		tag: 'img', src: data, style:'margin:10px;visibility:hidden;width:400px; height:400px;'
	}, true).show(true).frame();
};

var store = new Ext.data.JsonStore({
	url: '/index.php?action=listshopphtos',
	root: 'images',
	fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date', dateFormat:'timestamp'}]
});


var tpl = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumb-wrap" id="{name}">',
'<div class="thumb"><img src="{url}" title="{name}" height="100"></div>',
'<span><a href="#" onclick=zz("{name}")>увеличить</a></span></div>',
'</tpl>',
'<div class="x-clear"></div>'
);

var ima = new Ext.DataView({
	store: store,
	tpl: tpl,
	autoHeight:true,
	singleSelect: true,
	// multiSelect: true,
	overClass:'x-view-over',
	itemSelector:'div.thumb-wrap',
	emptyText: 'Нет фотографий',

	prepareData: function(data){
		data.shortName = Ext.util.Format.ellipsis(data.name, 15);
		data.sizeString = Ext.util.Format.fileSize(data.size);
		data.dateString = data.lastmod.format("m/d/Y g:i a");
		return data;
	}
});

var panel = new Ext.Panel({
	id:'images-view',
	frame:true,
	baseCls:'x-plain',
	width:450,
	autoHeight:true,
	collapsible:false,
	layout:'fit',
	title:'Фотографии',
	items: ima
});

var store2 = new Ext.data.JsonStore({
	url: '/index.php',
	root: 'results',
	totalProperty:'total',
	fields: ['name', 'url']
});
var GallerypB = new Ext.PagingToolbar({
	pageSize: 10,

	cls: 'x-plain',
	store: store2

});

var tpl2 = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumb-wrap" id="{name}">',
'<div class="thumb"><img src="{url}" title="{name}" height="100"></div>',
'<span><a href="#" onclick=zz2("{name}")>увеличить</a></span></div>',
'</tpl>',
'<div class="x-clear"></div>'
);

var ima2 = new Ext.DataView({
	store: store2,
	tpl: tpl2,
	autoHeight:true,
	singleSelect: true,
	// multiSelect: true,
	overClass:'x-view-over',
	itemSelector:'div.thumb-wrap',
	emptyText: 'Нет фотографий',

	prepareData: function(data){
		data.shortName = Ext.util.Format.ellipsis(data.name, 15);

		return data;
	}
});

var panel2 = new Ext.Panel({
	id:'images-view',
	frame:true,
	width:450,
	autoHeight:true,
	collapsible:false,
	baseCls: 'x-plain',
	layout:'fit',

	title:'Фотографии',
	items: [ima2]
});
function stors(start, stop, id)
{
	store2.load({params:{start:stop, limit:start, id: id, task:'GalleryGetImages'}});
}

function cartpr(id)
{

	var ima2 = new Ext.DataView({
		store: store,
		tpl: tpl,
		autoHeight:true,
		singleSelect: true,
		// multiSelect: true,
		overClass:'x-view-over',
		itemSelector:'div.thumb-wrap',
		emptyText: 'Нет фотографий',

		prepareData: function(data){
			data.shortName = Ext.util.Format.ellipsis(data.name, 15);
			data.sizeString = Ext.util.Format.fileSize(data.size);
			data.dateString = data.lastmod.format("m/d/Y g:i a");
			return data;
		}
	});

	var panel2 = new Ext.Panel({
		id:'images-view',
		frame:true,

		width:535,

		autoHeight:true,
		collapsible:true,
		layout:'fit',
		title:'Фотографии',
		items: ima2
	});

	store.load({params:{id: id }});
	var pr = new Ext.Panel({
		autoLoad: {url: 'pr.php?iditem='+id},
		autoWidth: true

	});
	var pre = new Ext.Window({
		width: '600',
		height: '800',
		//autoWidth: true,
		//autoHeight: true,
		items: [pr, panel2]
	});

	//pre.show();
	pre.show();




	//ima.refresh();



};
function zz(file)
{
	new Ext.Window({
		layout:'fit',
		width:500,

		autoHeight:true,
		// modal: true,
		// shadow:true,
		// closable: false,
		resizable: true,
		plain: true,
		html:'<center><img src="/files/shop/'+file+'" width="90%">',
		border: false
	}).show();
}
function zz2(file)
{
	new Ext.Window({
		layout:'fit',
		width:'40%',

		autoHeight:true,
		// modal: true,
		// shadow:true,
		// closable: false,
		resizable: true,
		plain: true,
		html:'<center><img src="/files/gallery/'+file+'" width="90%">',
		border: false
	}).show();
}
function mailto(id)
{
	var div = new Ext.Component({
		autoEl: { tag: 'div', html: '<center><font color="RED">* </font>- обязательно для заполнения</center>', width: '130',
		autoShow: true
		}});
		var formemail = new Ext.FormPanel({
			labelAlign:'top',
			autoWidth: true,
			frame:true,
			bodyStyle:'padding:5px 5px 0',
			autoHeight: true,
			monitorValid:true,
			items:[{
				layout:'column',
				items:[{
					columnWidth:.5,
					layout: 'form',
					items: [
					{xtype:'hidden', name:'id', value: id},
					{
						xtype:'textfield',
						fieldLabel: 'Контактное лицо <font color="RED">*</font>',
						name: 'name',
						allowBlank: false
					},
					{
						xtype:'textfield',
						fieldLabel: 'Компания',
						name: 'company',
						allowBlank: true
					},
					{
						xtype:'textfield',
						fieldLabel: 'Телефон',
						name: 'tel',
						allowBlank: true
					}

					]},
					{
						columnWidth:.5,
						layout: 'form',
						items: [
						{
							xtype:'textfield',
							fieldLabel: 'Факс',
							name: 'fax',
							allowBlank: true
						},
						{
							xtype:'textfield',
							fieldLabel: 'E-mail <font color="RED">*</font>',
							name: 'email',
							vtype: 'email',
							allowBlank: false
						},
						{
							xtype:'textfield',
							fieldLabel: 'Город',
							name: 'city',
							allowBlank: true
						}
						]

					}]},
					{
						xtype:'textarea',
						fieldLabel: 'Сообщение <font color="RED">*</font>',
						name: 'text',
						anchor:'90%',
						allowBlank: false
					},div

					],
					buttonAlign:'center',
					buttons: [{
						text: 'Отправить',
						formBind: true,

						handler: function()
						{
							formemail.getForm().submit({
								url: '/index.php',
								waitMsg: 'Пожалуйста, подождите...',
								params: {task:'CompanyEmailed'},
								method: 'POST',
								success: function()
								{
									formemail.getForm().reset();
									Ext.getCmp('WindowEmailCompany').close();
									Ext.MessageBox.alert('', 'Сообщение успешно отправлено');

								}
							});
						}
					}]
		});
		var win = new Ext.Window({
			layout:'fit',
			width:400,
			id: 'WindowEmailCompany',
			modal: true,
			shadow:true,
			closeAction: 'close',
			resizable: true,
			plain: true,
			items: formemail
		}).show();
}


Ext.onReady(function(){


	Ext.QuickTips.init();
	Ext.BLANK_IMAGE_URL = '/images/n.gif';
	if (Ext.get('GalleryOnIndex'))
	{
		Ext.get("GalleryOnIndex").on("mousedown", Ext.emptyFn, null, {delegate:"a"});
		Ext.get("GalleryOnIndex").on("click", Ext.emptyFn, null, {delegate:"", preventDefault:true});
	}
	if (Ext.get('mail'))
	{
		Ext.get("mail").on("mousedown", Ext.emptyFn, null, {delegate:"a"});
		Ext.get("mail").on("click", Ext.emptyFn, null, {delegate:"", preventDefault:true});
	}
	else
	{

	}

	var Tree = Ext.tree;
	var tree = new Tree.TreePanel({
		autoScroll:true,
		animate:true,
		rootVisible: false,
		border: false,
		autoHeight: true,
		id: 'ShopTree',
		containerScroll: true,
		lines: false,
		trackMouseOver: false,
		animCollapse: true,
		loadMask: true,
		style: '',
		loader: new Ext.tree.TreeLoader({url:'/index.php?remote=tree', loadMask: true}),
		root: {
			nodeType: 'async',
			text: 'Ext JS',
			draggable:false,
			id:'0'
		}
	});
	if (Ext.get('expan'))
	{
		Ext.get('expan').on('click', function() {
			
			if (Ext.get('collapse'))
			{
				Ext.DomHelper.overwrite(this, {tag: 'span', html: 'Открыть все категории', id:'collapsefalse'}, true).show();
				tree.collapseAll();
			}
			else
			{
				Ext.DomHelper.overwrite(this, {tag: 'span', html: 'Закрыть все категории', id:'collapse'}, true).show();
				tree.expandAll();
				
			}
		});
	}

	if (Ext.get('ShopTree'))
	{
		tree.render('ShopTree');
		tree.getRootNode().expand();
	}
	var lostpass = new Ext.Component({
		autoEl: { tag: 'span', html: '<a href="/reg/"><b>Регистрация</b></a> <a href="/lostpass/"><b>Забыли&nbsp;пароль?</b></a>'
		}});
		var loginform = new Ext.FormPanel({
			labelWidth:80,
			url:'/index.php',
			frame:false,
			border:false,
			baseCls:'x-plain',
			defaultType:'textfield',
			monitorValid:true,
			//buttonAlign: 'center',

			items:[{
				fieldLabel:'Email',
				name:'email',
				vtype:'email',
				allowBlank:false
			},{
				fieldLabel:'Пароль',
				name:'pass',
				inputType:'password',
				allowBlank:false
			},lostpass],
			buttons:[{
				text:'Войти',
				formBind: true,
				handler:function(){
					loginform.getForm().submit({
						method:'POST',
						params: {task: 'LoginTo'},
						waitTitle: 'Инцилизация',
						waitMsg: 'Подаждите пожалуйста...',
						success:function(){
							window.open('/userinfo/', '_SELF');
						},
						failure: function(){
							Ext.MessageBox.alert('Ошибка','Логин или пароль не правильны');
						}
					});
				}
			}]
		});
		if (Ext.get('XAuthUser'))
		{
			loginform.render('XAuthUser');
		}

		if (Ext.get('SearchForm'))
		{
			var SF = Ext.get('SearchForm');
			// SF.dom.value.setOpacity(50);
			SF.on('click', function(e, t){t.value ="";});
		}
});

function getCity(select)
{
	var s = Ext.get(select);
	
	
	if (s.dom.value!=0)
	{
	var to = s.dom.value;
	var city = Ext.get(to).dom.innerHTML;
	Ext.get('hiddenCity').dom.value=city;
	var weight = Ext.get('weight').dom.value;
	var w = Math.floor(weight);
	if (!Ext.isEmpty(to))
	{
		
		
	if (to=="city--moskva")
	{
		if (weight<1){
			var price = 250;
			var total = Math.floor(Ext.get('total').dom.value);
			 Ext.get('price-dost').update(price);
			 Ext.get('price-dost-value').dom.value = price;
			 var totalW = Math.floor(total+price);
			 Ext.get('total-with-dost').update(totalW);
			 var z = Ext.get('ves-iz').dom.innerHTML;
			 z = "(вес до 1 кг, доставка курьером)";
			 Ext.get('price-rub').update(' рублей '+z);
			 Ext.get('hiddenPriceDost').dom.value=z;
			 Ext.get('price-rub2').update(' рублей');
			 return true;
		}
		
	}
		
   Ext.Ajax.request({
		url:'http://emspost.ru/api/rest?method=ems.calculate&from=city--moskva&to='+to+'&weight='+weight,
		scriptTag: true,
		success:function(o)
		{
	       var res = Ext.decode(o.responseText);
	       if (res.rsp)
	       {
	    	   if (res.rsp.stat)
	    	   {
	    		   if (res.rsp.stat=="ok"){
	    			   var price =Math.floor(res.rsp.price);
	    			   
	    			   if (to=="city--moskva")
	    			   {
	    				  if (price<250){
	    					  var price = Math.floor(250);
	    				  }
	    			   }
	    			   
	    			   var min = res.rsp.term.min;
	    			   var max = res.rsp.term.max;
	    			   var total = Math.floor(Ext.get('total').dom.value);
	    			   Ext.get('price-dost').update(price);
	    			   Ext.get('price-dost-value').dom.value = price;
	    			   var totalW = Math.floor(total+price);
	    			   Ext.get('total-with-dost').update(totalW);
	    			   var z = Ext.get('ves-iz').dom.innerHTML;
	    			   z = "(вес "+z+" кг, по тарифу EMS)";
	    			   Ext.get('price-rub').update(' рублей '+z);
	    			   Ext.get('hiddenPriceDost').dom.value=z;
	    			   Ext.get('price-rub2').update(' рублей');
	    			 //  Ext.get('day-dost').update('от '+min+' до '+max+' дней');
	    		   }
	    		   else{
	    			   Ext.MessageBox.alert('', 'Слишком большой вес')
	    		   }
	    	   }
	       }
		}
	});
	}
	}
	else{
		Ext.get('hiddenCity').dom.value="";
		Ext.get('price-dost').update('Не выбран город');
		Ext.get('price-rub').update('');
		Ext.get('price-rub2').update('');
		 Ext.get('hiddenPriceDost').dom.value='';
		var total = Math.floor(Ext.get('total').dom.value);
		Ext.get('total-with-dost').update('Не выбран город');
	   // Ext.get('day-dost').update('---');
	}
	
	
}


