/* This program is written by pronojit roy (kolkata,india)**/
var ua = navigator.userAgent.toLowerCase();
var IsIE = (ua.indexOf('msie')>-1);
var IsFF = (document.implementation && document.implementation.createDocument);

String.prototype.trim=function(){ return this.replace(/^\s+|\s+$/,''); };
String.prototype.htmlEncode=function(){ return this.replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); };
String.prototype.htmlDecode=function(){ return this.replace(/&gt;/g,'>').replace(/&lt;/g,'<').replace(/&quot;/g,'"').replace(/&amp;/g,'&'); };
String.prototype.isEmpty=function(){ return (this.toString().length==0); }

function ByID(id){ return document.all? document.all[id] : document.getElementById(id); }
function T(e,t){ var item = (typeof e=='object') ? e : ByID(e) ; if(IsIE){item.innerText=t;}else{item.textContent=t;} }
function IsError(e) { return(((e.parseError && e.parseError.errorCode && e.parseError.reason && e.parseError.url && e.parseError.errorCode!=0)||0)!=0); }
function ErrorMessage(e) { return (e.parseError.reason + '\n' + e.parseError.url); }

// Some function releated to AJAX
if (window.ActiveXObject && !window.XMLHttpRequest) {
    window.XMLHttpRequest = function() {
        return new ActiveXObject((ua.indexOf("msie 5") != -1)?"Microsoft.XMLHTTP":"Msxml2.XMLHTTP");
    };
}
if (window.ActiveXObject && !window.XMLDOMDocument) {
    window.XMLDOMDocument = function() {
        var c = ['MSXML2.DOMDocument.3.0','MSXML2.DOMDocument','MSXML.DOMDocument','Microsoft.XMLDOM'];
        for(var i=0;i<c.length;i++){
            try{
			    xmldom = new ActiveXObject(c[i]);
			    return xmldom;
			}catch(err){
				alert(err.description);
		    }
        }
        return null;
    };
}
function XmlHttp(){
	var xmlhttp = new window.XMLHttpRequest();	
	var Parent = this;
	var isCompleted = false;
	if(xmlhttp!=null){
		xmlhttp.onreadystatechange = function(){
			if(xmlhttp.readyState==4){
				//debugger;
				if(isCompleted==false){
					Parent.OnCompleted(xmlhttp.responseText);
				}
				isCompleted = true;
			} 
			Parent.OnStateChange(xmlhttp.readyState);
		};	
	}

	this.OnCompleted = function(e){alert('Pl attach event  - (value get by default event) = ' + e.toString())};

	this.Post = function(UrlPage,QueryValues){
		isCompleted = false;
		try {
			xmlhttp.open("POST",UrlPage, true);
			xmlhttp.setRequestHeader("Method", "POST " + UrlPage + " HTTP/1.1");
			xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");	
			xmlhttp.setRequestHeader("Content-length", (QueryValues||'').length);
			xmlhttp.send(QueryValues)
		}catch(err){
			alert('Error On Post Method : ' +  (err.description||err||'*'));
		}
	}

	this.Get = function(UrlPage,QueryValues){
		isCompleted = false;
		debugger;
		if(QueryValues!=null && QueryValues.length>0){
			UrlPage = UrlPage + "?" + QueryValues
		}
		try {
			xmlhttp.open("GET",UrlPage,false);
			xmlhttp.send("");
		}catch(err){
			alert('Error On Get Method : ' +  (err.description||err||'*'));
		}
	};	
	this.OnStateChange = function(result){	
		if(window.status){
			switch(result){
				case 0 ://Uninitialized
					window.status='';
				break;
				case 1:// Open
					window.status='Opening...';
				break;
				case 2:// Sent
					window.status='Sending...';
				break;
				case 3:// Receiving
					window.status='Receiving...';
				break;
				case 4:// Loaded
					window.status='';
				break;
			}	
		}
	};
	return this;
}
/**********************************************************************/
function isValidPhone(t) {
e = 0;
// Convert into a string and check that we were provided with something
if (t == null || t == undefined  || t.toString().length == 0) { e = 1;  return false; }
// Don't allow country codes to be included (assumes a leading "+")
var x = /^(\+)[\s]*(.*)$/;
if (x.test(t)) { e = 2;  return false; }
// Remove spaces from the telephone number to help validation
while (t.indexOf(" ")!= -1)  { t = t.slice (0,t.indexOf(" ")) + t.slice (t.indexOf(" ")+1) }  
// Remove hyphens from the telephone number to help validation
while (t.indexOf("-")!= -1)  {  t = t.slice (0,t.indexOf("-")) + t.slice (t.indexOf("-")+1) }  
// Now check that all the characters are digits
x = /^[0-9]{10,11}$/
if (!x.test(t)) { e = 3;  return false; }
// Now check that the first digit is 0
x = /^0[0-9]{9,10}$/
if (!x.test(t)) {  e = 4;  return false; }  
// Finally check that the telephone number is appropriate.
x = /^(01|02|03|05|070|075|077|07624|078|079)[0-9]+$/;
if (!x.test(t)) { e = 5; return false; }
return true; }
/**********************************************************************/

function UrlString(){
	var allValues = null;
	var url = location.search;
	var lastName = null;
	var lastIndex = null;
	if(location.search && location.search.length>1){
		allValues = location.search.toUpperCase().substr(1).split('&');
	}
	this.Exists = function(e){
		if(allValues==null || e==null) return null;
		e = e.toUpperCase();
		lastName = e; lastIndex = null;
		for(ti=0;ti< allValues.length;ti++){
			var keyvalue = allValues[ti].split('=');
			if(keyvalue.length>1){
				if(keyvalue[0]==e){ lastIndex = ti; return true; }
			}
		}
		return false;
	}
	this.Value = function(e){
		if(allValues==null || e==null) return null;
		e = e.toUpperCase();
		for(ti = ((lastName==e && lastIndex!=null) ? lastIndex : 0) ;ti<allValues.length;ti++){
			var keyvalue = allValues[ti].split('=');
			if(keyvalue.length>1){
				if(keyvalue[0]==e){ return keyvalue[1]; }
			}
		}
		return null;
	}	
	return this;
}

function IsStructureOK(s,e){
	var E = function(e){return e.toString().length==0;}
	if(ByID('StructureOK') && ByID('StructureOK').value=='true') { return true; }		
	var m = [];
	if(s.Url==null){ m[m.length] = 'Url not declare'; }
	if(s.E==null){ m[m.length] = 'E not declare'; }
	if(s.L==null){ m[m.length] = 'L not declare'; }
	if(s.P==null){ m[m.length] = 'P not declare'; }
	if(s.AAS==null){ m[m.length] = 'AAS not declare'; }
	if(s.Fields==null){ m[m.length] = 'Fields not declare'; }
	if(m.length>0) return alert(m.join('\n'));
	if(E(s.Url)) { m[m.length] = 'Url value missing.';  }
	if(E(s.E)) { m[m.length] = 'E value missing.';  }
	if(E(s.L)) { m[m.length] = 'L value missing.';  }
	if(E(s.P)) { m[m.length] = 'P value missing.';  }
	if(E(s.AAS)) { m[m.length] = 'AAS value missing.';  }
	if(m.length>0) return alert(m.join('\n'));
	if(parseInt(s.E)<0) { m[m.length] = 'Value of E can\'t be less than zero.';  }
	if(parseInt(s.L)<0) { m[m.length] = 'Value of L can\'t be less than zero.';  }
	if(parseInt(s.P)<0) { m[m.length] = 'Value of P can\'t be less than zero.';  }
	for(fi=0;fi<s.Fields.length;fi++){
		var f = s.Fields[fi]
		if(f.Name==null) { m[m.length] = 'Name not declare in array index ' + fi.toString();}
		if(f.Name){
		    if(f.Name.Submit==null){ m[m.length] = 'Submit not declare inside Name in array index ' + fi.toString();}
		    if(f.Name.Input==null){ m[m.length] = 'Input not declare inside Name in array index ' + fi.toString();}
		} 		
		if(f.Required==null) { m[m.length] = 'Required not declare in array index ' + fi.toString();}
		if(f.Required){
		    if(f.Required.Check==null){ m[m.length] = 'Check not declare inside Required in array index ' + fi.toString();}
		    if(f.Required.Check && f.Required.Message==null) { m[m.length] = 'RequiredMessage not declare in array index ' + fi.toString();}    
		}		
	}
	if(m.length>0) return alert(m.join('\n'));
	for(fi=0;fi<s.Fields.length;fi++){
		var f = s.Fields[fi]
		if(E(f.Name.Submit)) { m[m.length] = 'Submit value missing inside Name in array index ' + fi.toString();}
		if(E(f.Name.Input)) { m[m.length] = 'InputName value missing inside Name in array index ' + fi.toString();} 		
		if(E(f.Required.Check)) { m[m.length] = 'Required value missing in array index ' + fi.toString();} 		
		if(f.Required.Check && E(f.Required.Message)){ m[m.length] = 'Message value missing inside Required in array index ' + fi.toString();} 
		if(f.Custom){
		    if(f.Custom.Check && E(f.Custom.Message)){ m[m.length] = 'Message value missing inside Custom in array index '+ fi.toString(); } 
		}
	}
	if(m.length>0) return alert(m.join('\n'));
	for(fi=0;fi<s.Fields.length;fi++){
		var f = s.Fields[fi]
		if(ByID(f.Name.Input)==null){ m[m.length] = f.Name.Input + ' not found in page.'; }
	}
	if(m.length>0) return alert(m.join('\n'));
	ByID('StructureOK').value ='true';
	return true;
}
function CheckAndSubmitData(s,e,c){
	var E = function(e){return e.toString().length==0;}
	var A = function(m,e) { if(e==null){ alert(m.join('\n')); }else{ e(m); } return false; }
	var V = function(e) { return ByID(e).value.trim().htmlEncode(); }
	if(IsStructureOK(s,e)){
		var m = [];
		for(fi=0;fi<s.Fields.length;fi++){
			var f = s.Fields[fi];
			var v = ByID(f.Name.Input).value;
			if(f.Required.Check && E(v)){
				m[m.length]=f.Required.Message;
			}
			if(f.Custom && f.Custom.Check && E(v)==false){
				if(typeof(f.Custom.Check)=='string'){
					var r = new RegExp(f.Custom.Check);
					if(!(r.test(v))) { m[m.length] = f.Custom.Message; }
				}else if(typeof(f.Custom.Check)=='function'){
					if(!(f.Custom.Check(v))) { m[m.length] = f.Custom.Message; }
				}else{
					if(f.Custom.Check.test && !(f.Custom.Check.test(v))) { m[m.length] = f.Custom.Message; }
				}
			}
		}
		if(m.length>0) return A(m,e); 
		var urlstrings = new UrlString();
		if(urlstrings.Exists('E')){ tmpValue = urlstrings.Value('E'); if (isNaN(tmpValue)==false && parseInt(tmpValue)){ s.E = tmpValue; } }
		if(urlstrings.Exists('L')){ tmpValue = urlstrings.Value('L'); if (isNaN(tmpValue)==false && parseInt(tmpValue)){ s.L = tmpValue; } }
		if(urlstrings.Exists('P')){ tmpValue = urlstrings.Value('P'); if (isNaN(tmpValue)==false && parseInt(tmpValue)){ s.P = tmpValue; } }
		var Q = 'Url=' + s.Url + '&E=' + s.E + '&L=' + s.L + '&P=' + s.P + '&AAS=' + s.AAS
		for(fi=0;fi<s.Fields.length;fi++){
			var f = s.Fields[fi]
			Q += "&"  + f.Name.Submit + "=" + V(f.Name.Input);
		}
		var req = new XmlHttp();
		if(urlstrings.Exists('DEBUG') && urlstrings.Value('DEBUG')=='1'){
			Q = Q + "&DEBUG=1";
			if(c) req.OnCompleted = function(e){alert(e);c(e);};
		}else{
			if(c) req.OnCompleted = function(e){c(e);};
		}		
		req.Post("http://mybeautyguide.totally.info/submitdata.php?"+Math.random(),Q);
		return true;
	}
	return false;
}

