///////////////////////////////////////////////////////////////////////////
var cp = new Ext.state.CookieProvider({
   path: "/",
   expires: new Date(new Date().getTime()+(1000*60*60*24*365)), //365 days
});
function load_order_data() {
	Ext.Ajax.request({
		url: '/order/getajax',
        success: function(resp) {
			data = Ext.decode(resp.responseText);
			fieldShipName.setValue(data.order_name);
			fieldShipPhone.setValue(data.order_phone);
			fieldShipZip.setValue(data.order_zip);
			fieldShipCity.setValue(data.order_city);
			fieldShipStreet.setValue(data.order_street);
			fieldShipDesc.setValue(data.order_description);
			if (data.shipping_method)
				shipping_methodCombo.setValue(data.shipping_method);
			if (data.order_country)
				order_countryCombo.setValue(data.order_country);

			if (data.invoice==1) { 
				fieldInvocie.setValue(true);
			}
			else {
				fieldInvocie.setValue(false);
			}
			fieldInvocieName.setValue(data.invoice_name);
			fieldInvocieZip.setValue(data.invoice_zip);
			fieldInvocieCity.setValue(data.invoice_city);
			fieldInvocieStreet.setValue(data.invoice_street);
			
			fieldCassaProductPrice.setValue(data.products_price+" Ft.");
			fieldCassaShipPrice.setValue(data.shipping_price+" Ft.");
			fieldCassaOrderPrice.setValue(data.order_price+" Ft.");
			ShipPrice = data.shipping_price;
			OrderPrice = data.order_price;
			
			_gaq.push(['_setCustomVar',
			           1,             		// This custom var is set to slot #1.  Required parameter.
			           'User Email',     	// The name of the custom variable.  Required parameter.
			           data.order_email,	// Sets the value of "User Type" to "Member" or "Visitor" depending on status.  Required parameter.
			            2             		// Sets the scope to session-level.  Optional parameter.
			        ]);
			_gaq.push(['_setCustomVar',
			           1,             		// This custom var is set to slot #1.  Required parameter.
			           'User City',     	// The name of the custom variable.  Required parameter.
			           data.order_city,		// Sets the value of "User Type" to "Member" or "Visitor" depending on status.  Required parameter.
			            2             		// Sets the scope to session-level.  Optional parameter.
			        ]);
			
			//CIB TEST
			if (data.order_email=='balazs.szabo@gmail.com' || data.order_email=='k.enesz@gmail.com' || data.order_email=='gergely.somfai@gmail.com' || data.order_email=='info@bioszallito.hu' || data.order_email=='info@ajandekora.hu' || data.order_email=='jucamuca@gmail.com') {
				paystore = new Ext.data.ArrayStore({
			        id: 0,
			        fields: [
			            'myId',
			            'displayText'
			        ],
			        data: [['cod', 'Utánvét'], ['bank_transfer', 'Bankártyás fizetés (Visa/Mastercard)']]        
			    });
				cp.set( 'sokoweb_user', 1 );
			}
			else {
				paystore = new Ext.data.ArrayStore({
			        id: 0,
			        fields: [
			            'myId',
			            'displayText'
			        ],
			        data: [['cod', 'Utánvét']]
			    });
			}
			payment_methodCombo.store = paystore;
		}
	});	
}
var ShipPrice=0;
var OrderPrice=0;
var order_accordion_default_active=0;
var logined = 0;
function user_is_logined() { 				
	load_order_data();
	panelLoginReg.hide();
	panelInvoiceData.show();
	panelCassa.show();
	panelShipData.show();
	order_accordion_default_active=1;
	logined = 1;
	_gaq.push(['_setCustomVar',
	           1,             // This custom var is set to slot #1.  Required parameter.
	           'User Type',   // The name of the custom variable.  Required parameter.
	           'Member',      // Sets the value of "User Type" to "Member" or "Visitor" depending on status.  Required parameter.
	            2             // Sets the scope to session-level.  Optional parameter.
	        ]);
}
//////////////////////////////////////////////////////////////////////////////
Ext.apply(Ext.form.VTypes, {
	password: function(val, field) {
		if (field.initialPassField) {
			var pwd = Ext.getCmp(field.initialPassField);
			return (val == pwd.getValue());
		}
		return true;
	},
	passwordText: 'A mező tartalma nem egyezik meg az előzőével',
	emailText: 'Ez a mező egy emailcímet vár! mint pl. "user@example.com"'
});

var fieldLoginEmail = new Ext.form.TextField({
	id:'loginemail',
	fieldLabel: 'Email',
    name: 'loginemail',
    vtype:'email',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
var fieldLoginPassword = new Ext.form.TextField({
    id: 'loginpassword',
	fieldLabel: 'Jelszó',
    name: 'loginpassword',
    inputType:'password',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!'
});
fieldLoginPassword.on("specialkey", specialKey_fieldLoginPassword, this);
function specialKey_fieldLoginPassword(value,e) {
  if ( e.getKey() == e.RETURN || e.getKey() == e.ENTER )
  {
	  clickloginbutton();
  }
}
function clickloginbutton() {
	Ext.Ajax.request({
        url: '/user/login',
        method: 'POST',
        success: function(resp) {
			data = Ext.decode(resp.responseText);
			if (data.success) {
				user_is_logined();
				_gaq.push(['_trackEvent', 'User', 'Login', fieldLoginEmail.getValue()]);
				order_accordion.layout.setActiveItem(3);
			}
			else {
//				Ext.MessageBox.alert('Sikertelen belépés', data.errors.reason);
				login_fail(fieldLoginEmail.getValue());
			}
		},
		failure: function (resp) {
			login_fail(fieldLoginEmail.getValue());
//			data = Ext.decode(resp.responseText);
//			Ext.MessageBox.alert('Sikertelen belépés', data.errors.reason);
//			_gaq.push(['_trackEvent', 'User', 'LoginFail', fieldLoginEmail.getValue()]);
		},
        params: {
			login_email: fieldLoginEmail.getValue(),
			login_password: fieldLoginPassword.getValue()
        }
  });
}
var panelLogin = new Ext.form.FormPanel({
	x: 50,
    y:75,
    width:300,
    border:false,
	items:[fieldLoginEmail,fieldLoginPassword],
	buttons: [{text: 'Belépés', 		
		handler: clickloginbutton 
	}]
});

var panelLoginWrap = new Ext.Panel({
	title: 'Belépés',
	width:400,
	region:'west',
	layout:'absolute',
	items:[panelLogin]
});
////////////////////////////////
var fieldRegName = new Ext.form.TextField({
	id: 'regname',
	fieldLabel: 'Név',
    name: 'regname',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'    
});
var fieldRegEmail = new Ext.form.TextField({
	id: 'regemail',
	fieldLabel: 'Email',
    name: 'regemail',
    vtype:'email',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
var fieldRegPassword = new Ext.form.TextField({
    id: 'regpassword',
	fieldLabel: 'Jelszó',
    name: 'regpassword',
    inputType:'password',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!'
});
var fieldRegPassword2 = new Ext.form.TextField({
    id: 'regpassword2',
	fieldLabel: 'Jelszó ismét',
    name: 'regpassword2',
    inputType:'password',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    vtype:'password',
    msgTarget:'side',
    initialPassField:'regpassword'
});

var panelReg = new Ext.form.FormPanel({
	x: 50,
    y:75,
    width:300,
    border:false,
    url:'/user/reg',
	items:[fieldRegName,fieldRegEmail,fieldRegPassword,fieldRegPassword2],
	buttons: [{text: 'Regisztráció', 
		handler: function () {
			//TODO VALIDATE
			//fieldRegEmail.validate(); 
			//if (fieldRegEmail.getValue()==fieldRegEmail2.getValue()) AND (fieldRegEmail2.getValue()!='')
			Ext.Ajax.request({
                url: '/user/reg',
                method: 'POST',
                success: function(resp) {
					data = Ext.decode(resp.responseText);
					if (data.success) {
						user_is_logined();
						order_accordion.layout.setActiveItem(1);
						_gaq.push(['_trackEvent', 'User', 'Register', fieldRegEmail.getValue()]);
					}
					else {
						Ext.MessageBox.alert('Sikertelen regisztráció', data.errors.reason);
						_gaq.push(['_trackEvent', 'User', 'RegisterFail', fieldRegEmail.getValue()]);
					}
				},
				failure: function (resp) {
					data = Ext.decode(resp.responseText);
					Ext.MessageBox.alert('Sikertelen regisztráció', data.errors.reason);
					_gaq.push(['_trackEvent', 'User', 'RegisterFail', fieldRegEmail.getValue()]);
				},
                params: {
					reg_name:  fieldRegName.getValue(),
					reg_email: fieldRegEmail.getValue(),
					reg_password: fieldRegPassword.getValue()
                }
              });
		}
	}]
});

var panelRegWrap = new Ext.Panel({
	title: 'Regisztráció',
	region:'center',
	width:400,
	layout:'absolute',
	items:[panelReg]
});

////////////////////////////////


var panelLoginReg = new Ext.Panel({
	title: 'Belépés  /Regisztráció',
	layout: 'border',
	items:[panelLoginWrap,panelRegWrap]
});
////////////////////////////////////////////////////////////////////////////////////////////////
var fieldShipName = new Ext.form.TextField({
	id:'shipname',
	fieldLabel: 'Név',
    name: 'shipname',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
var fieldShipPhone = new Ext.form.TextField({
	id:'shipphone',
	fieldLabel: 'Telefon',
    name: 'shipphone',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
//order_country	order_county
var order_countryCombo = new Ext.form.ComboBox({
    fieldLabel: 'Ország',
    typeAhead: true,
    width:140,
    triggerAction: 'all',
    lazyRender:true,
    editable:false,
    name:'order_country',
    mode: 'local',
    store: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'myId',
            'displayText'
        ],
        data: [['AF','Afghanistan'],['AL','Albania'],['DZ','Algeria'],['AS','American Samoa'],['AD','Andorra'],['AO','Angola'],['AI','Anguilla'],['AQ','Antarctica'],['AG','Antigua And Barbuda'],['AR','Argentina'],
               ['AM','Armenia'],['AW','Aruba'],['AU','Australia'],['AT','Austria'],['AZ','Azerbaijan'],['BS','Bahamas'],['BH','Bahrain'],['BD','Bangladesh'],['BB','Barbados'],['BY','Belarus'],['BE','Belgium'],
               ['BZ','Belize'],['BJ','Benin'],['BM','Bermuda'],['BT','Bhutan'],['BO','Bolivia'],['BA','Bosnia And Herzegovina'],['BW','Botswana'],['BV','Bouvet Island'],['BR','Brazil'],
               ['IO','British Indian Ocean Territory'],['BN','Brunei'],['BG','Bulgaria'],['BF','Burkina Faso'],['BI','Burundi'],['KH','Cambodia'],['CM','Cameroon'],['CA','Canada'],['CV','Cape Verde'],
               ['KY','Cayman Islands'],['CF','Central African Republic'],['TD','Chad'],['CL','Chile'],['CN','China'],['CX','Christmas Island'],['CC','Cocos (Keeling) Islands'],['CO','Columbia'],['KM','Comoros'],
               ['CG','Congo'],['CK','Cook Islands'],['CR','Costa Rica'],['CI','Cote D\'Ivorie (Ivory Coast)'],['HR','Croatia (Hrvatska)'],['CU','Cuba'],['CY','Cyprus'],['CZ','Czech Republic'],
               ['CD','Democratic Republic Of Congo (Zaire)'],['DK','Denmark'],['DJ','Djibouti'],['DM','Dominica'],['DO','Dominican Republic'],['TP','East Timor'],['EC','Ecuador'],['EG','Egypt'],['SV','El Salvador'],
               ['GQ','Equatorial Guinea'],['ER','Eritrea'],['EE','Estonia'],['ET','Ethiopia'],['FK','Falkland Islands (Malvinas)'],['FO','Faroe Islands'],['FJ','Fiji'],['FI','Finland'],['FR','France'],
               ['FX','France, Metropolitan'],['GF','French Guinea'],['PF','French Polynesia'],['TF','French Southern Territories'],['GA','Gabon'],['GM','Gambia'],['GE','Georgia'],['DE','Germany'],['GH','Ghana'],
               ['GI','Gibraltar'],['GR','Greece'],['GL','Greenland'],['GD','Grenada'],['GP','Guadeloupe'],['GU','Guam'],['GT','Guatemala'],['GN','Guinea'],['GW','Guinea-Bissau'],['GY','Guyana'],['HT','Haiti'],
               ['HM','Heard And McDonald Islands'],['HN','Honduras'],['HK','Hong Kong'],['HU','Hungary'],['IS','Iceland'],['IN','India'],['ID','Indonesia'],['IR','Iran'],['IQ','Iraq'],['IE','Ireland'],['IL','Israel'],
               ['IT','Italy'],['JM','Jamaica'],['JP','Japan'],['JO','Jordan'],['KZ','Kazakhstan'],['KE','Kenya'],['KI','Kiribati'],['KW','Kuwait'],['KG','Kyrgyzstan'],['LA','Laos'],['LV','Latvia'],['LB','Lebanon'],
               ['LS','Lesotho'],['LR','Liberia'],['LY','Libya'],['LI','Liechtenstein'],['LT','Lithuania'],['LU','Luxembourg'],['MO','Macau'],['MK','Macedonia'],['MG','Madagascar'],['MW','Malawi'],['MY','Malaysia'],
               ['MV','Maldives'],['ML','Mali'],['MT','Malta'],['MH','Marshall Islands'],['MQ','Martinique'],['MR','Mauritania'],['MU','Mauritius'],['YT','Mayotte'],['MX','Mexico'],['FM','Micronesia'],['MD','Moldova'],
               ['MC','Monaco'],['MN','Mongolia'],['MS','Montserrat'],['MA','Morocco'],['MZ','Mozambique'],['MM','Myanmar (Burma)'],['NA','Namibia'],['NR','Nauru'],['NP','Nepal'],['NL','Netherlands'],
               ['AN','Netherlands Antilles'],['NC','New Caledonia'],['NZ','New Zealand'],['NI','Nicaragua'],['NE','Niger'],['NG','Nigeria'],['NU','Niue'],['NF','Norfolk Island'],['KP','North Korea'],
               ['MP','Northern Mariana Islands'],['NO','Norway'],['OM','Oman'],['PK','Pakistan'],['PW','Palau'],['PA','Panama'],['PG','Papua New Guinea'],['PY','Paraguay'],['PE','Peru'],['PH','Philippines'],
               ['PN','Pitcairn'],['PL','Poland'],['PT','Portugal'],['PR','Puerto Rico'],['QA','Qatar'],['RE','Reunion'],['RO','Romania'],['RU','Russia'],['RW','Rwanda'],['SH','Saint Helena'],
               ['KN','Saint Kitts And Nevis'],['LC','Saint Lucia'],['PM','Saint Pierre And Miquelon'],['VC','Saint Vincent And The Grenadines'],['SM','San Marino'],['ST','Sao Tome And Principe'],['SA','Saudi Arabia'],
               ['SN','Senegal'],['SC','Seychelles'],['SL','Sierra Leone'],['SG','Singapore'],['SK','Slovak Republic'],['SI','Slovenia'],['SB','Solomon Islands'],['SO','Somalia'],['ZA','South Africa'],
               ['GS','South Georgia And South Sandwich Islands'],['KR','South Korea'],['ES','Spain'],['LK','Sri Lanka'],['SD','Sudan'],['SR','Suriname'],['SJ','Svalbard And Jan Mayen'],['SZ','Swaziland'],
               ['SE','Sweden'],['CH','Switzerland'],['SY','Syria'],['TW','Taiwan'],['TJ','Tajikistan'],['TZ','Tanzania'],['TH','Thailand'],['TG','Togo'],['TK','Tokelau'],['TO','Tonga'],['TT','Trinidad And Tobago'],
               ['TN','Tunisia'],['TR','Turkey'],['TM','Turkmenistan'],['TC','Turks And Caicos Islands'],['TV','Tuvalu'],['UG','Uganda'],['UA','Ukraine'],['AE','United Arab Emirates'],['UK','United Kingdom'],
               ['US','United States'],['UM','United States Minor Outlying Islands'],['UY','Uruguay'],['UZ','Uzbekistan'],['VU','Vanuatu'],['VA','Vatican City (Holy See)'],['VE','Venezuela'],['VN','Vietnam'],
               ['VG','Virgin Islands (British)'],['VI','Virgin Islands (US)'],['WF','Wallis And Futuna Islands'],['EH','Western Sahara'],['WS','Western Samoa'],['YE','Yemen'],['YU','Yugoslavia'],['ZM','Zambia'],
               ['ZW','Zimbabwe']]
    }),
    valueField: 'myId',
    value:['HU'],
    displayField: 'displayText'
});
var fieldShipZip = new Ext.form.NumberField({
	id:'shipzip',
	fieldLabel: 'Irányítószám',
    name: 'shipzip',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
var fieldShipCity = new Ext.form.TextField({
	id:'shipcity',
	fieldLabel: 'Város',
    name: 'shipcity',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
var fieldShipStreet = new Ext.form.TextField({
	id:'shipstreet',
	fieldLabel: 'Utca',
    name: 'shipstreet',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
var fieldShipDesc = new Ext.form.TextArea({
	id:'shipdesc',
	fieldLabel: 'Megjegzés',
    name: 'shipdesc',
    maxLength: 255,
    width:250,
    height: 150
    
});
var shipping_methodCombo = new Ext.form.ComboBox({
    fieldLabel: 'Átvétel módja',
    typeAhead: true,
    width:250,
    triggerAction: 'all',
    lazyRender:true,
    editable:false,
    name:'shipping_method',
    mode: 'local',
    store: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'myId',
            'displayText'
        ],
        data: [['futar_free', 'Ingyenes futárszolgálat (Magyarországra 0 Ft.)'], ['no_ship', 'Telephelyen átvétel (1077 Bp. Wesselényi u. 31)']]
    }),
    valueField: 'myId',
    value:['futar_free'],
    displayField: 'displayText'
});
var panelShipLeft  = new Ext.form.FormPanel({
	x: 50,
    y:50,
    width:300,
    border:false,
	items:[fieldShipName,fieldShipPhone,order_countryCombo,fieldShipZip,fieldShipCity,fieldShipStreet]
});

var panelShipLeftWrap = new Ext.Panel({
	title: '',
	region:'center',
	width:400,
	layout:'absolute',
	items:[panelShipLeft]
});

var panelShipRight = new Ext.form.FormPanel({
	x: 20,
	y:40,
	width:380,
	border:false,
	items:[fieldShipDesc,shipping_methodCombo]
});

var panelShipRightWrap = new Ext.Panel({
	title: '',
	region:'east',
	width:400,
	layout:'absolute',
	items:[panelShipRight]
});
var panelShipData = new Ext.Panel({
    title: 'Szállítási adatok',
    hidden: true,
    layout: 'border',
    items:[panelShipLeftWrap,panelShipRightWrap],
    buttons:[{text: 'Fizetés / Megrendelés', width:250,iconCls:'order_next',
    	handler: function () {
    		//TODO Validálni az adatokat
			Ext.Ajax.request({
	            url: '/order/updateship',
	            method: 'POST',
	            success: function(resp) {
					load_order_data();
					order_accordion.layout.setActiveItem(3);
				},
				params: {
					order_name: fieldShipName.getValue(),
					order_phone: fieldShipPhone.getValue(),
					order_country: order_countryCombo.getValue(),
					order_zip: fieldShipZip.getValue(),
					order_city: fieldShipCity.getValue(),
					order_street: fieldShipStreet.getValue(),
					order_description: fieldShipDesc.getValue(),
					shipping_method: shipping_methodCombo.getValue()
		        }
			});
    	}
    }]
});
//////////////////////////////////////////////////////////////////////////////////////////////
var fieldInvocieName = new Ext.form.Field({
	id:'fieldInvocieName',
	fieldLabel: 'Név',
    name: 'fieldInvocieName',
    allowBlank:false,
    msgTarget:'side'
});
   
var fieldInvocieZip = new Ext.form.Field({
	id:'fieldInvocieZip',
	fieldLabel: 'Irányítószám',
    name: 'fieldInvocieZip',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
var fieldInvocieCity = new Ext.form.Field({
	id:'fieldInvocieCity',
	fieldLabel: 'Város',
    name: 'fieldInvocieCity',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
var fieldInvocieStreet = new Ext.form.Field({
	id:'fieldInvocieStreet',
	fieldLabel: 'Utca',
    name: 'fieldInvocieStreet',
    allowBlank:false,
    blankText : 'Ezt a mezőt kötelező kitölteni!',
    msgTarget:'side'
});
var fieldInvocie = new Ext.form.Checkbox({
	id:'fieldInvocie',
    checked: false,
    fieldLabel: 'Igen, áfás számlát kérek!',
    labelSeparator: '',
    name: 'fieldInvocie'
});
var panelInvocieLeft = new Ext.form.FormPanel({
	x: 20,
	y:40,
	width:380,
	border:false,
	items:[fieldInvocieName,fieldInvocieZip,fieldInvocieCity,fieldInvocieStreet]
});
var panelInvoiceLeftWrap = new Ext.Panel({
	title: '',
	region:'center',
	width:400,
	layout:'absolute',
	items:[panelInvocieLeft]
});
////
var panelInvoiceRight = new Ext.form.FormPanel({
	x: 20,
	y:40,
	width:380,
	border:false,
	items:[fieldInvocie]
});

var panelInvoiceRightWrap = new Ext.Panel({
	title: '',
	region:'east',
	width:400,
	layout:'absolute',
	items:[panelInvoiceRight]
});
///
var panelInvoiceData = new Ext.Panel({
    title: 'Számlázási adatok',
    hidden: true,
    layout: 'border',
    items:[panelInvoiceLeftWrap,panelInvoiceRightWrap],
    buttons:[{text: 'Fizetés / Megrendelés', width:250,iconCls:'order_next',
    	handler: function () {
    		//TODO Validálni az adatokat
    		var Invoice = 0
    		if (fieldInvocie.getValue()) Invoice = 1;
			Ext.Ajax.request({
	            url: '/order/setinvoice',
	            method: 'POST',
	            success: function(resp) {
					load_order_data();
					order_accordion.layout.setActiveItem(3);
				},
				params: {
					invoice: Invoice,
					invoice_name: fieldInvocieName.getValue(),
					invoice_zip: fieldInvocieZip.getValue(),
					invoice_city: fieldInvocieCity.getValue(),
					invoice_street: fieldInvocieStreet.getValue(),
		        }
			});
    	}
    }]
});




//////////////////////////////////////////////////////////////////////////////////////////////
var fieldCassaProductPrice = new Ext.form.Field({
	id:'fieldCassaProductPrice',
	fieldLabel: 'Kosár összege'
});
var fieldCassaShipPrice = new Ext.form.Field({
	id:'fieldCassaShipPrice',
	fieldLabel: 'Szállítási költség'
});
var fieldCassaOrderPrice = new Ext.form.Field({
	id:'fieldCassaOrderPrice',
	fieldLabel: 'Végösszeg',
	style:'font-weight:bold'
});
var payment_methodCombo = new Ext.form.ComboBox({
    fieldLabel: 'Fizetés módja',
    typeAhead: true,
    width:250,
    triggerAction: 'all',
    lazyRender:true,
    editable:false,
    name:'payment_method',
    mode: 'local',
    store: new Ext.data.ArrayStore({
        id: 0,
        fields: [
            'myId',
            'displayText'
        ],
//        data: [['cod', 'Utánvét'], ['bank_transfer', 'Banki átutalás(121212-112134433234-121221)']]
        data: [['cod', 'Utánvét']]
//        data: [['cod', 'Utánvét'], ['bank_transfer', 'Bankártyás fizetés (Visa/Mastercard)']]        
    }),
    valueField: 'myId',
    value:['cod'],
    displayField: 'displayText'
});
var panelCassaLeft = new Ext.form.FormPanel({
	x: 20,
	y:40,
	width:380,
	border:false,
	items:[fieldCassaProductPrice,fieldCassaShipPrice,fieldCassaOrderPrice,payment_methodCombo]
});
var panelCassaLeftWrap = new Ext.Panel({
	title: '',
	region:'west',
	width:400,
	layout:'absolute',
	items:[panelCassaLeft]
});
///////
var panelCassaRight = new Ext.Panel({
	x:10,
	y:0,
	width:400,
	border:false,
	html: '<iframe style="overflow:scroll;width:360px;height:280px; border:0px solid red;" frameborder="1" src="/page/joginyilatkozat/nolayout/1"></iframe>'
});
var panelCassaRightWrap = new Ext.Panel({
	title: '',
	region:'center',
	width:400,
	layout:'absolute',
	items:[panelCassaRight]
});
///////
var cassaButton = new Ext.Button({
	text: 'A feltételeket elfogadom, Fizetés / Megrendelés', width:250,iconCls:'order_buy',
	handler: function () {
	var Invoice = 0
	if (fieldInvocie.getValue()) Invoice = 1;
	//Validálni az adatokat
	if (
		( (shipping_methodCombo.getValue()!='no_ship') && (!fieldShipName.isValid() || !fieldShipPhone.isValid() ||  
														 !order_countryCombo.isValid() || !fieldShipZip.isValid() || 
														 !fieldShipCity.isValid() || !fieldShipStreet.isValid() ) )
		||
		( (shipping_methodCombo.getValue()=='no_ship') && (!fieldShipName.isValid() || !fieldShipPhone.isValid() ) )
		) {
		order_accordion.layout.setActiveItem(1);
		alert('Hibásan , vagy részlegesen töltötte ki a vásárlói adatokat!');
		return;
	}
	
	if (fieldInvocie.getValue() && (fieldInvocieName.getValue()=='' || fieldInvocieZip.getValue()=='' || fieldInvocieCity.getValue()=='' || fieldInvocieStreet.getValue()=='')) {
		order_accordion.layout.setActiveItem(2);
		alert('Hibásan , vagy részlegesen töltötte ki a számlázási adatokat!');
		return;
	}

	
	//GOOGLE ECOMRECE TRACK
	_gaq.push(['_trackPageview']);
	_gaq.push(['_addTrans',
	           CartStore.getAt(0).data.order_id,    // order ID - required
	           'WebShop',  							// affiliation or store name
	           OrderPrice,						    // total - required
	           '25',           						// tax
	           ShipPrice,      						// shipping
	           fieldShipCity.getValue(),       		// city
	           '',     								// state or province
	           order_countryCombo.getValue()        // country
	         ]);
	var products_list = CartStore.getRange(0,CartStore.getCount());
	for (var item=0;item<=CartStore.getCount()-1;item++){
		_gaq.push(['_addItem',
		           products_list[item].data.order_id,       // order ID - required
		           products_list[item].data.product_id,     // SKU/code - required
		           products_list[item].data.product_name,   // product name
		           '',    			  				// category or variation
		           products_list[item].data.price,          // unit price - required
		           products_list[item].data.quantity        // quantity - required
		         ]);
	}
	_gaq.push(['_trackTrans']); //submits transaction to the Analytics servers
	//GOOGLE ECOMRECE TRACK END
	if (payment_methodCombo.getValue()=='bank_transfer') {
		Ext.Ajax.request({
            url: '/cibbank/creatnewtransaction/',
            method: 'POST',
            success: function(resp) {
				data = Ext.decode(resp.responseText);
				document.location = data.url; 
			},
			params: {
				order_name: fieldShipName.getValue(),
				order_phone: fieldShipPhone.getValue(),
				order_country: order_countryCombo.getValue(),
				order_zip: fieldShipZip.getValue(),
				order_city: fieldShipCity.getValue(),
				order_street: fieldShipStreet.getValue(),
				order_description: fieldShipDesc.getValue(),
				shipping_method: shipping_methodCombo.getValue(),
				
				invoice: Invoice,
				invoice_name: fieldInvocieName.getValue(),
				invoice_zip: fieldInvocieZip.getValue(),
				invoice_city: fieldInvocieCity.getValue(),
				invoice_street: fieldInvocieStreet.getValue(),
				
				payment_method: payment_methodCombo.getValue()
	        }
		});
	}
	else {
		Ext.Ajax.request({
            url: '/order/buy',
            method: 'POST',
            success: function(resp) {
				_gaq.push(['_trackPageview', "/order/buy"]); //GOOGLE ANALYTICS track
				_gaq.push(['_trackEvent', 'Order', 'Buy']);
				Ext.Msg.show({
			        title:' Rendelés üzenet ',
			        msg: 'Köszönjük rendelését!',
			        buttons: Ext.Msg.OK,
			        fn: function(btn, text) {
					document.location = "/";
			        },
			        animEl: 'elId',
			        icon: Ext.MessageBox.WARNING
			      });
			},
			params: {
				order_name: fieldShipName.getValue(),
				order_phone: fieldShipPhone.getValue(),
				order_country: order_countryCombo.getValue(),
				order_zip: fieldShipZip.getValue(),
				order_city: fieldShipCity.getValue(),
				order_street: fieldShipStreet.getValue(),
				order_description: fieldShipDesc.getValue(),
				shipping_method: shipping_methodCombo.getValue(),
				
				invoice: Invoice,
				invoice_name: fieldInvocieName.getValue(),
				invoice_zip: fieldInvocieZip.getValue(),
				invoice_city: fieldInvocieCity.getValue(),
				invoice_street: fieldInvocieStreet.getValue(),
				
				payment_method: payment_methodCombo.getValue()
	        }
		});
	}
}
});
var panelCassa = new Ext.Panel({
    title: 'Fizetés / Megrendelés',
    hidden: true,
    layout: 'border',
    items:[panelCassaLeftWrap,panelCassaRightWrap],
    buttons:[cassaButton]
});
//////////////////////////////////////////////////////////////////////////////////////////////
var order_accordion = new Ext.Panel({
    region:'south',
    height:400,
    margins:'5 0 5 5',
    split:true,
    layout:'accordion',
    items: [panelLoginReg, panelShipData, panelInvoiceData, panelCassa]
});


var order_window = new Ext.Window({
	title	  : 'Rendelés',
    modal     : true,
    autoTabs  : true,
    proxyDrag : true,
    resizable : false,
    width     : 800,
    height    : 600,
    autoScroll: false,
    closeAction: 'hide',
    shadow    : false,
    frame     : true,
//    defaultType: 'textfield',
    layout    : 'border',
    items     : [cart_block_cm_grid,order_accordion]
  });
 
order_window.on('show',function() {//eltüntetjük a top flash banner ha van mert bezavar
	var obj = document.getElementById('top_flash_banner');
	if (obj!=null) {
		obj.style.display = 'none';
	}
});
order_window.on('hide',function() {//eltüntetjük a top flash banner ha van mert bezavar
	var obj = document.getElementById('top_flash_banner');
	if (obj!=null) {
		obj.style.display = 'block';
	}
	_gaq.push(['_trackEvent', 'Order', 'CloseOrderWin', '']);
});

