/*
 * Copyright(c) 2009, Soft Idiom Limtied
 * www.softidiom.com and www.4dsites.com
*/

//Ehances html form fields that contain an ext apptribute.

var Forms = {
	
	init: function() {
		Ext.BLANK_IMAGE_URL = '/shared/ext/v2.2/resources/images/default/s.gif';
		Ext.QuickTips.init();
		Forms.request = Ext.urlDecode(window.location.search.substring(1));
		Forms.page = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
		Forms.pageName = Forms.page.substring(0,Forms.page.lastIndexOf('.'));
		Forms.folders = window.location.pathname.split('/');
		Forms.parentFolder = Forms.folders[Forms.folders.length-3];
		Forms.folder = Forms.folders[Forms.folders.length-2];
		Forms.initStores();
	},
		
	initStores: function() {
		//titles
		this.titleStore = new Ext.data.SimpleStore({
        fields: ['name'],
	        data : [['Mr'], ['Miss'], ['Mrs'],['Ms'],['Dr']]
	    });
		this.countriesStore = new Ext.data.SimpleStore({
        fields: ['name'],
	        data : [["Afghanistan"],["Aland Islands"],["Albania"],["Algeria"],["American Samoa"],["Andorra"],["Angola"],["Anguilla"],["Antarctica"],["Antigua And Barbuda"],["Argentina"],["Armenia"],["Aruba"],["Australia"],["Austria"],["Azerbaijan"],["Bahamas"],["Bahrain"],["Bangladesh"],["Barbados"],["Belarus"],["Belgium"],["Belize"],["Benin"],["Bermuda"],["Bhutan"],["Bolivia"],["Bosnia And Herzegovina"],["Botswana"],["Bouvet Island"],["Brazil"],["British Indian Ocean Territory"],["Brunei Darussalam"],["Bulgaria"],["Burkina Faso"],["Burundi"],["Cambodia"],["Cameroon"],["Canada"],["Cape Verde"],["Cayman Islands"],["Central African Republic"],["Chad"],["Chile"],["China"],["Christmas Island"],["Cocos (keeling) Islands"],["Colombia"],["Comoros"],["Congo"],["Congo\, The Democratic Republic Of The"],["Cook Islands"],["Costa Rica"],["Cote D'ivoire"],["Croatia"],["Cuba"],["Cyprus"],["Czech Republic"],["Denmark"],["Djibouti"],["Dominica"],["Dominican Republic"],["Ecuador"],["Egypt"],["El Salvador"],["Equatorial Guinea"],["Eritrea"],["Estonia"],["Ethiopia"],["Falkland Islands (malvinas)"],["Faroe Islands"],["Fiji"],["Finland"],["France"],["French Guiana"],["French Polynesia"],["French Southern Territories"],["Gabon"],["Gambia"],["Georgia"],["Germany"],["Ghana"],["Gibraltar"],["Greece"],["Greenland"],["Grenada"],["Guadeloupe"],["Guam"],["Guatemala"],["Guernsey"],["Guinea"],["Guinea-bissau"],["Guyana"],["Haiti"],["Heard Island And Mcdonald Islands"],["Honduras"],["Hong Kong"],["Hungary"],["Iceland"],["India"],["Indonesia"],["Iran, Islamic Republic Of"],["Iraq"],["Ireland"],["Isle Of Man"],["Israel"],["Italy"],["Jamaica"],["Japan"],["Jersey"],["Jordan"],["Kazakhstan"],["Kenya"],["Kiribati"],["Korea, Democratic People's Republic Of"],["Korea, "],["epublic Of"],["Kuwait"],["Kyrgyzstan"],["Lao People's Democratic Republic"],["Latvia"],["Lebanon"],["Lesotho"],["Liberia"],["Libyan Arab Jamahiriya"],["Liechtenstein"],["Lithuania"],["Luxembourg"],["Macao"],["Macedonia, The Former Yugoslav Republic Of"],["Madagascar"],["Malawi"],["Malaysia"],["Maldives"],["Mali"],["Malta"],["Marshall Islands"],["Martinique"],["Mauritania"],["Mauritius"],["Mayotte"],["Mexico"],["Micronesia, Federated States Of"],["Moldova"],["Monaco"],["Mongolia"],["Montenegro"],["Montserrat"],["Morocco"],["Mozambique"],["Myanmar"],["Namibia"],["Nauru"],["Nepal"],["Netherlands"],["Nethe"],["lands Antilles"],["New Caledonia"],["New Zealand"],["Nicaragua"],["Niger"],["Nigeria"],["Niue"],["Norfolk Island"],["Northern Mariana Islands"],["Norway"],["Oman"],["Pakistan"],["Palau"],["Palestinian Territory, Occupied"],["Panama"],["Papua New Guinea"],["Paraguay"],["Peru"],["Philippines"],["Pitcairn"],["Poland"],["Portugal"],["Puerto Rico"],["Qatar"],["REunion"],["Romania"],["Russian Federation"],["Rwanda"],["Saint BarthElemy"],["Saint Helena"],["Saint Kitts And Nevis"],["Saint Lucia"],["Saint Martin"],["Saint Pierre And Miquelon"],["Saint Vincent And The Grenadines"],["Samoa"],["San Marino"],["Sao Tome And Principe"],["Saudi Arabia"],["Senegal"],["Serbia"],["Seychelles"],["Sierra Leone"],["Singapore"],["Slovakia"],["Slovenia"],["Solomon Islands"],["Somalia"],["South Africa"],["South Georgia And The South Sandwich Islands"],["Spain"],["Sri Lanka"],["Sudan"],["Suriname"],["Svalbard And Jan Mayen"],["Swaziland"],["Sweden"],["Switzerland"],["Syrian Arab Republic"],["Taiwan, Province Of China"],["Tajikistan"],["Tanzania, United Republic Of"],["Thailand"],["Timor-leste"],["Togo"],["Tokelau"],["Tonga"],["Trinidad And Tobago"],["Tunisia"],["Turkey"],["Turkmenistan"],["Turks And Caicos Islands"],["Tuvalu"],["Uganda"],["Ukraine"],["United Arab Emirates"],["United Kingdom"],["United States"],["United States Minor Outlying Islands"],["Uruguay"],["Uzbekistan"],["Vanuatu"],["Vatican City State"],["Venezuela"],["Viet Nam"],["Virgin Islands\, British"],["Virgin Islands, U.S."],["Wallis And Futuna"],["Western Sahara"],["Yemen"],["Zambia"],["Zimbabwe"]]
	    });
		this.referalStore = new Ext.data.SimpleStore({
        fields: ['name'],
	        data : [['Google Search'], ['Yahoo Search'], ['Bing Search'],['Ask Search'],['MSN/Live Search'],['Website Link'],['Friend or Colleague'],['Banner Advert'],['Magazine Advert'],['TV Advert'],['Press Announcement'],['Other']]
	    });
		this.timetocallStore = new Ext.data.SimpleStore({
        fields: ['name'],
	        data : [['Any'],['Daytime'],['Morning'],['Lunchtime'],['Afternoon'],['Evening']]
	    });
		this.budgetStore = new Ext.data.SimpleStore({
        fields: ['name'],
	        data : [['&pound;500 - &pound;1,000'], ['&pound;1,000 - &pound;2,500'], ['&pound;2,500 - &pound;5,000'],['&pound;5,000 - &pound;8,000'],['&pound;8,000 - &pound;10,000'],['&pound;10,000 - &pound;15,000'],['&pound;15,000 - &pound;20,000'],['&pound;20,000 - &pound;30,000'],['&pound;30,000 - &pound;40,000'],['&pound;40,000 - &pound;50,000'],['Over &pound;50,000']]
	    });
		this.deadlineStore = new Ext.data.SimpleStore({
        fields: ['name'],
	        data : [['As soon as possible'],['Withing 1 month'], ['Withing 2 months'], ['Withing 3 months'],['Withing 4 months'],['Withing 5 months'],['Withing 6 months'],['Over 6 months']]
	    });
		/*this.userStore = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: '/site/phplib/get_user.php'
			}),
			// create reader that reads the records    
			reader: new Ext.data.JsonReader({
				root: 'results',
				totalProperty: 'total',
				id: 'id',
				fields: ['id','username','hint','administrator','company_name','uws_company_id','firstname','surname','title','phone']
			}),
			sortInfo: {field:'id', direction:'ASC'},
			remoteSort: true
		});
		this.userStore.on('load',Forms.storesLoaded);
		this.userStore.load();*/
		Forms.storesLoaded();
	},
		
	storesLoaded: function() {
		//Forms.userData = Forms.userStore.getAt(0).data;
		Forms.enhanceHTMLForms();
	},
	
	enhanceHTMLForms: function() {
		//find all form fields with an ext attribute and convert it into an Ext form field, using the properties defined in the attribute value
		Forms.getInputs();
		var items = '',sep = '';
		for (var i = 0; i < Forms.inputs.length; i++) {
			items+=(sep+'{applyTo:"'+Forms.inputs[i].getAttribute("id")+'",'+Forms.inputs[i].getAttribute("ext")+',id:\''+Forms.inputs[i].getAttribute("id")+'\'}');
			sep=',';
		}
		items = eval('['+items+']');
		this.form = new Ext.FormPanel({
			style: 'display:none',
	        items: items
		});
		this.form.render(document.body);
		//bind data in bound fields
		//Ext.getCmp('update-firstname').setValue('Hello');
	},

	getInputs: function(){
		//Get all inputs that have an ext attribute
		this.inputs = [];
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].getAttribute("ext")) {
				this.inputs.push(inputs[i]);
			}
		}
		var textareas = document.getElementsByTagName("textarea");
		for (var i = 0; i < textareas.length; i++) {
			if (textareas[i].getAttribute("ext")) {
				this.inputs.push(textareas[i]);
			}
		}
	},

	passwordconfirmValidator: function(field,value) {
		var form = field.el.id.split('-')[0];
		//if there is a form-password field, ensure this field value matches
		var passwordField = Ext.getCmp(form+'-password');
		if(passwordField && passwordField.getValue() == value) {
			return true;
		}
		return 'The password fields are not the same.';
	},

	updatepasswordconfirmValidator: function(field,value) {
		var form = field.el.id.split('-')[0];
		//if there is a form-password field, ensure this field value matches
		var passwordField = Ext.getCmp(form+'-update_password');
		if(passwordField && passwordField.getValue() == value) {
			return true;
		}
		return 'The password fields are not the same.';
	},

	mustBeChecked: function(field) {
		//validator that ensures a checkbox is checked
		if(field.getValue()) {
			return true;
		} else {
			return 'You must check this box to proceed';
		}
	},

	postForm: function(formid) {
		var form = Ext.getDom(formid);
		var flds = form.elements;
		var data = {form: form.name};
		var errors = [];
		for(i=0;i<flds.length; i++) {
			var f = flds[i];
			var extField = Ext.getCmp(f.id);
			if(extField && !extField.isValid()) {errors.push(extField.name)}
			if(f.name && extField) {
				if(extField.isXType('combo')) {
					data[f.name+'_id'] = extField.getValue();
					data[f.name] = extField.getRawValue();
				} else {
					data[f.name] = extField.getValue();
				}
			} else { //other non-ext fields
				data[f.name] = f.value;
			}
		}
		if(errors.length > 0) {
			Ext.Msg.show({
				title:'This Form Contains Errors',
				msg: 'Some of the information is missing or incorrect. Please correct the fields marked with<br /><br /><span class="x-form-invalid x-form-focus" style="padding:2px;">red underlines</span></b>',
				buttons: Ext.Msg.OK,
				icon: Ext.MessageBox.WARNING
			});
			return;
		}
		Ext.Ajax.request({
			url: '/site/phplib/processFormPost.php',
			scope: this,
			params: {data: Ext.util.JSON.encode(data)},
			success: function(response, opts) {
		   	   //post failed, report the problem
			   if(!Ext.decode(response.responseText).success) {
			   	button.disabled = false;
				Ext.Msg.show({
					title:'Error Processing Form',
					msg: Ext.decode(response.responseText).message,
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.WARNING
				});
				return;
			   }
				//post success - replace the form with the response
				Site.scrollToTop();
				form.parentNode.innerHTML = Ext.decode(response.responseText).message;
				pageHeight=500;
				$('page-mask').setStyle('height',pageHeight+'px');
				$('page-container').setStyle('height',pageHeight + 'px');
			},
			failure: function(response, opts) {
				button.disabled = false;
				Ext.Msg.show({
					title:'Failed to post this form',
					msg: 'We were unable to make a connection with our server. The may a be caused by a problem with your Internet connection or our server may be undergoing maintenace.<br /><br /><hr /><br /><b>Please wait a few minutes and try again. If the problem persists contact us for assistence.</b>',
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.WARNING
				});
			}
		});
	}
	
}

var previous_onload;
if( window.onload ) {
    previous_onload = window.onload;
}
window.onload = function () {
    if( previous_onload ) {
        previous_onload();
    }
    Forms.init();
}
