var MWJ_progBar = 0;


var calltimLeft = 0;
var smsLeft = 0;
var timLeft = 0;
var reqAction = "start";
var successUrl = "";
var showProgressBar = 1;
var smsMode = 0;
var sFile = "inc/simulate.php";
var rFile = "getReq.php";
var currentMod = "";
var state = 0;
var minsLeft = 0;
var secsLeft = 0;
var simStatus = 0;


function addzero(a){
	if(a<=9) {
		b = '0'+a;
	} else {
		b = a;
	}
	return b;
}

function countDown(mcxtime){
	if(mcxtime>0) {
		if(mcxtime > 0) {
			mcxtime -= 1;
			if(mcxtime > 3599) {
				hoursLeft = Math.floor(mcxtime / 3600);
				tmpSecs = Math.floor(mcxtime % 3600);
				minsLeft = Math.floor(tmpSecs / 60);
				secsLeft = tmpSecs % 60;
				var dispTime = addzero(hoursLeft) + ':' + addzero(minsLeft) + ':' + addzero(secsLeft);
			} else if(mcxtime > 59) {
				minsLeft = Math.floor(mcxtime / 60);
				secsLeft = mcxtime % 60;
				var dispTime = addzero(minsLeft) + ':' + addzero(secsLeft);
			} else {
				var dispTime = '00:' + addzero(mcxtime);
			}
			if(typeof($('cDisplay')) != 'undefined') {
				$('cDisplay').innerHTML = dispTime;
				cdTimer = setTimeout("countDown("+mcxtime+")",1000);
			}
		} 
	} /*else {
		$('cDisplay').innerHTML = "00:00";
	}*/
}


function startbar(calltime,duration){
	state = calltime/duration;
	
	
	if(simMode==1) {
		if(simStatus==0) {loadMod('callbutt', 'modules/callbutt_inactive.php');loadMod('hangupbutt', 'modules/hangupbutt.php');}
		simStatus = 1;
	}
	if(simMode==1 && state >= 1 && smsMode==0){
		simulate(orderNumber, 'callstopped');
		loadMod('callbutt', 'modules/callbutt.php');
		loadMod('hangupbutt', 'modules/hangupbutt_inactive.php');
	}
	window.myProgBar.setBar(state);
	calltime+=1;
	calltimLeft = duration-calltime + 1;
	if(calltimLeft >= 0) {
		getTimeLeft(calltimLeft);
		bartimer = setTimeout("startbar("+calltime+","+duration+")",1000);
	}
}
function setBarStatus(curr,max){
	var smsstate=curr/max;
	window.myProgBar.setBar(smsstate);
	smsLeft = max - curr;
	getTimeLeft(smsLeft);
}
function stopbar(){
	if(simMode==1) {
		simStatus = 0;
	}
	clearTimeout(bartimer);
}

function $(id) {
    return document.getElementById(id);
} 
function trim (vString) {
      vString = vString.replace(/^( )*/,"");
      vString = vString.replace(/( )*$/,"");
      return vString;
}

function trimAll (vString) {
      vString = vString.replace(/ /,"");
      return vString;
}

function startReq(ordno, urlCode, sUrl, reqAct) {
	if(sUrl) {
		successUrl = sUrl;
	}
	if(reqAct) {
		if(reqAct=="connected"||reqAct=="simulate") {reqAction = reqAct;}
		getReq(ordno, urlCode);
	}  else {
		reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",10000);
	}
	
}
function startReqNoProgress(ordno, urlCode, sUrl, reqAct) {
	showProgressBar = 0;
	if(reqAct) {
		reqAction = reqAct;
		startReq(ordno, urlCode, sUrl, reqAct);
	}
	
}

function startSMSReq(ordno, urlCode, sUrl, reqAct) {
	
	smsMode = 1;
	if(sUrl) {
		successUrl = sUrl;
	}
	if(reqAct) {
		if(reqAct=="connected"||reqAct=="simulate") {reqAction = reqAct;}
		getReq(ordno, urlCode);
	}  else {
		reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",10000);
	}
	
}
function startSMSReqNoProgress(ordno, urlCode, sUrl, reqAct) {
	showProgressBar = 0;
	smsMode = 1;
	if(reqAct) {
		reqAction = reqAct;
		startReq(ordno, urlCode, sUrl, reqAct);
	}
	
}


function getReq(ordno, urlCode) {
    var xmlhttp = false;
    var response;
    var reqURL = rFile+'?orderno='+ordno+'&action='+reqAction+'&urlCode='+urlCode;
    
        					
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			//xmlhttp = false;
			 xmlhttp = new XMLHttpRequest();
		}
	}
    if(smsMode == 1) {
    	reqURL += "&smsMode=1";
    } else if(dropCallMode==1) {
    	reqURL += "&dropCallMode=1";
    }
    xmlhttp.open("GET", reqURL, true);
	xmlhttp.onreadystatechange = function() {
	    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
	        response =  xmlhttp.responseText.split("%%%");
	        if(xmlhttp.responseText) {
	        	
	        		if(response[0] == "connected") {
	        			reqAction = "connected";
	        			if(showProgressBar == 1) {
	        					
	        				if(response[4].length==2 && country != response[4]) {
	        					location.href=('?'+js_string+'&orderno='+ordno);
        					}
	        				
	        				if(smsMode==1) {
	        					setBarStatus(parseInt(response[1]),parseInt(response[2]));
	        					showProgressInfo216();
	        					loadMod('pm', 'modules/cb.php?pm=sms&lang='+language);
	        				} else if(dropCallMode==1 && parseInt(response[3]) == 1) {
	        					if(typeof(window.myProgBar)!='undefined') {
	        						setBarStatus(parseInt(response[1]),parseInt(response[2]));
	        					}
	        					if(mcxtimeout == 0) {
	        						loadMod('pm', 'modules/cb.php?pm=call&lang='+language);
	        					}
	        				} else {
	        					if(dropCallMode==1 && parseInt(response[3]) == 0 ) {
	        						location.href=('?'+js_string+'&orderno='+ordno);
	        					}
	        					startbar(parseInt(response[1]),parseInt(response[2]));
	        					loadMod('pm', 'modules/cb.php?pm=call&lang='+language);
	        				}
	        				
	        				if(response[5] != "") {
        						loadMod('infoout', 'modules/info.php?imsg='+response[5]+"&"+response[7]+"&ordno="+ordno+'&lang='+language);
        					}
	        				if(response[6] != "") {
        						loadMod('infoout', 'modules/error.php?error='+response[6]+"&"+response[7]+"&ordno="+ordno+'&lang='+language);
        					}
	        				
	        			}
	        			reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",100);
	        			
	        		} else if(response[0] == "part") {
	        			 if(smsMode == 1) {
	        				if(nextSmsMsg == "mo") {
	        					loadMod('infoout', 'modules/info.php?imsg=text.sms.mo.nextmsg&lang='+language);
	        				}
	        				setBarStatus(parseInt(response[1]),parseInt(response[2]));
	        				reqAction = "start";
	        				reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",100);
	        			} else if(dropCallMode == 1) {
	        				loadMod('infoout', 'modules/info.php?imsg=text.onmore.call&lang='+language);
	        				setBarStatus(parseInt(response[1]),parseInt(response[2]));
	        				reqAction = "start";
	        				reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",100);
	        			} else  {
	        				loadMod('infoout', 'modules/info.php?imsg=text.global.new.callpart&lang='+language);
	        				if(showProgressBar == 1) {
		        				stopbar();
		        				reqAction = "start";
		            			reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",100);
		        			}
	        				
	        			}
	        		} else if(response[0] == "error")  {
	        			
	        			loadMod('infoout', 'modules/error.php?error='+response[1]+"&"+query_string+"&ordno="+ordno+response[2]+'&lang='+language);
	        			reqAction = "start";
	        			
	        			reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",100);
	        			
	        			
	        		} else if(response[0] == "info")  {
	        			
	        			if(response[2] != "" && response[3] != "") {
    						setBarStatus(parseInt(response[2]),parseInt(response[3]));
    					} 
	        			if(parseInt(response[1]) == 210) {
	        				reqAction = "connected";
	        			} else {
	        				reqAction = "start";
	        			}
	        			
	        			loadMod('infoout', 'modules/info.php?imsg='+response[1]+"&"+query_string+"&ordno="+ordno+'&lang='+language);
	        			reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",100);
	        			
	        				
	        			
	        		} else if(response[0] == "ok") {
	        			
	        			if(!successUrl) {
	        				successUrl = response[1];
	        			} 
	        			if(smsMode==1) {
	        				window.myProgBar.setBar(1);
	        			}
	        			/****
	        			 * 0->Direct API; 
	        			 * 2->Easy PIN; 
	        			 * 3->Easy Mail
	        			 ****/
	        			if(response[2]=='0') {
	        				thankyou();
	        				if(successUrl) {
	        					reloadTim = setTimeout("redirect('"+unescape(successUrl)+response[6]+"')",3000);
	        				}
	        				
	        			} else if(response[2]=='2') {
	        				loadPIN(successUrl, response[6], response[7], response[4]);
	        			
	        			} else if(response[2]=='3') {
	        				loadMail(successUrl, response[6]);
	        			}
	        			$('sysout').style.display='none';
	        			$('infoout').style.display='none';
	        			
	        		} else if(response[0] == "mcxtimeout") {
	        			
	        			successUrl = response[1];
	        			if(successUrl) {
	        				redirect(successUrl);
	        			}
	        			
	        		} else {
	        			if(showProgressBar == 1) {
	        				reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",100);
	        			}
	        		}
	       	}
	    } //else if(xmlhttp.status == 502) {
	    	//reloadTim = setTimeout("getReq('"+ordno+"', '"+urlCode+"')",10000);
	    //}
	}
    xmlhttp.send(null);
} 

function simulate(entordno, rAction) {
	
	if(trimAll(trim(entordno)) != orderNumber && rAction=="gotorderno") {
		alert("Order number invalid/expired!");
		return 0;
	} else {
		var xmlhttp = null;
	    var response;
	   if(smsMode == 1) {
	    	rAction = "sendsms";
	    	if(nextSmsMsg == "mt") {$('simButton').disabled=true;}
	    }
	    var sReqURL = sFile + '?action='+rAction+'&orderno='+orderNumber+'&phoneno='+ phoneNumber+'&kw='+ kw;
		

	    try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				//xmlhttp = false;
				 xmlhttp = new XMLHttpRequest();
			}
		}
		
		xmlhttp.open("GET", sReqURL, true);
		xmlhttp.onreadystatechange = function() {
		    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
		    	response =  xmlhttp.responseText;
		        if(response == "0") {
		       		alert("Can not connect to Server.");
		       		return 0;
		       	} 
		    } else {
		       	return 0;
		    }
		}
		xmlhttp.send(null);
	}
} 


function redirect(sUrl) {
	if(success_target=="self") { 
		self.location.href=sUrl;
	} else if(success_target=="top") { 
		top.location.href=sUrl;
	} else {
		success_target.location.href=sUrl;
	}
}
function saveWhatever(wform, target) {HTML_AJAX.formSubmit(wform, target);}
function thankyou() { HTML_AJAX.replace('main', 'modules/thankyou.php?lang='+language ); }
function loadPIN(url, params, pincode, ordno) { $('chooselang').style.display='none'; HTML_AJAX.replace('main', 'modules/pin.php?'+unescape(query_string)+'&pincode=' + pincode + '&url=' + url + '&method=' + params + '&orderno=' + ordno + '&lang='+language  ); $('sysout').style.display='block'; }
function loadMail(url, params) { $('chooselang').style.display='none'; HTML_AJAX.replace('main', 'modules/mail.php' + params + '&successurl=' + url + '&lang='+language + '&country='+country ); $('sysout').style.display='block'; }
function loadMod(id, url){if($(id)){HTML_AJAX.replace(id, url );if(id=='sysout'){$('sysout').style.display='block';}}}

function emailcheck(e) {
	
	res = (e.search('@') >= 1 && e.lastIndexOf('.') > e.search('@') && e.lastIndexOf('.') >= e.length-5 && e.lastIndexOf('.') != e.length-1 );
	if(res) {
		return true;
	} else 
	{
		alert(unescape(text_forms_fillemail));
	}
}

function clopen(id, stat) {
	
	if(typeof(stat)!='undefined') 
	{
		$(id).style.display = stat;
	}
	else {
		if($(id).style.display == 'block' ) 
		{
				$(id).style.display = 'none';
		} else 
		{
			$(id).style.display = 'block';
		}
	}
}

function loadModRel(qs) {
	alert(currentMod);
	if(currentMod=="help") { loadMod("main", "modules/help.php?"+qs); }
	if(currentMod=="cs_form") { loadMod("main", "modules/cs_form.php?"+qs); }
}
function sysclose() { $('sysout').style.display='none'; }

function progressCSForm(){
	var trim = new Function("s","while (s.substring(0,1)==' '){s = s.substring(1,s.length);} while (s.substring(s.length-1,s.length) == ' '){s = s.substring(0,s.length-1);}return s;");
	var f_populated = new Function("x", "return(x.length>0);");
	var message=trim(document.getElementById('message').value);
	var email=trim(document.getElementById('email').value);
	var phone=trim(document.getElementById('phone').value);
	var email_valid = email.match(/^(.+)@(.+)$/);
	if(!f_populated(email) || !f_populated(phone) || !f_populated(message)) alert(unescape(text_forms_fillall));
	else if(!email_valid) alert(unescape(text_forms_emailinvalid));
	else{ return 1; }
}

function getRefToDivNest( divID, oDoc ) {
	if( !oDoc ) { oDoc = document; }
	if( document.layers ) {
		if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
			for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
				y = getRefToDivNest(divID,oDoc.layers[x].document); }
			return y; } }
	if( $ ) { return $(divID); }
	if( document.all ) { return document.all[divID]; }
	return document[divID];
}

function progressBar( oBt, oBc, oBg, oBa, oWi, oHi, oDr ) {
	MWJ_progBar++; this.id = 'MWJ_progBar' + MWJ_progBar; this.dir = oDr; this.width = oWi; this.height = oHi; this.amt = 0;
	//write the bar as a layer in an ilayer in two tables giving the border
	document.write( '<table border="0" cellspacing="0" cellpadding="'+oBt+'"><tr><td bgcolor="'+oBc+'">'+
		'<table border="0" cellspacing="0" cellpadding="0"><tr><td height="'+oHi+'" width="'+oWi+'" bgcolor="'+oBg+'">' );
	if( document.layers ) {
		document.write( '<ilayer height="'+oHi+'" width="'+oWi+'"><layer bgcolor="'+oBa+'" name="MWJ_progBar'+MWJ_progBar+'"></layer></ilayer>' );
	} else {
		document.write( '<div style="position:relative;top:0px;left:0px;height:'+oHi+'px;width:'+oWi+'px;"><div id="percent" class="statcenter"></div>'+
			'<div class="stattext" style="position:absolute;z-index:5;top:0px;left:0px;height:0px;width:0px;padding:0px;text-align:center;background-color:'+oBa+';" id="MWJ_progBar'+MWJ_progBar+'"><div class="transparent">&nbsp;</div></div></div>' );
	}
	document.write( '</td></tr></table></td></tr></table>\n' );
	this.setBar = resetBar; //doing this inline causes unexpected bugs in early NS4
	this.setCol = setColour;
}
function resetBar( a, b ) {
	//work out the required size and use various methods to enforce it
	this.amt = ( typeof( b ) == 'undefined' ) ? a : b ? ( this.amt + a ) : ( this.amt - a );
	if( isNaN( this.amt ) ) { this.amt = 0; } if( this.amt > 1 ) { this.amt = 1; } if( this.amt < 0 ) { this.amt = 0; }
	var theWidth = Math.round( this.width * ( ( this.dir % 2 ) ? this.amt : 1 ) );
	var theHeight = Math.round( this.height * ( ( this.dir % 2 ) ? 1 : this.amt ) );
	var theDiv = getRefToDivNest( this.id ); if( !theDiv ) { window.status = 'Progress: ' + Math.round( 100 * this.amt ) + '%'; return; }
	if( theDiv.style ) { theDiv = theDiv.style; theDiv.clip = 'rect(0px '+theWidth+'px '+theHeight+'px 0px)'; }
	var oPix = document.childNodes ? 'px' : 0;
	theDiv.width = theWidth + oPix; theDiv.pixelWidth = theWidth; theDiv.height = theHeight + oPix; theDiv.pixelHeight = theHeight;
	if( theDiv.resizeTo ) { theDiv.resizeTo( theWidth, theHeight ); }
	theDiv.left = ( ( this.dir != 3 ) ? 0 : this.width - theWidth ) + oPix; theDiv.top = ( ( this.dir != 4 ) ? 0 : this.height - theHeight ) + oPix;
	
	
}
function setColour( a ) {
	//change all the different colour styles
	var theDiv = getRefToDivNest( this.id ); if( theDiv.style ) { theDiv = theDiv.style; }
	theDiv.bgColor = a; theDiv.backgroundColor = a; theDiv.background = a;
}

function setCookie(Name,Value,Duration){
  now = new Date();
  expiration = new Date(now.getTime()+Duration*86400000);
  document.cookie=Name+"="+Value+";expires="+expiration.toGMTString()+";";
}

function readCookie(Name){
  var searchname = Name + "=";
  var cookies = document.cookie.split(';');
  for(var i=0;i< cookies.length;i++){
   var singelcookie = cookies[i];
   while (singelcookie.charAt(0)==' ') singelcookie = singelcookie.substring(1,singelcookie.length);
     if(singelcookie.indexOf(searchname) == 0)
      return singelcookie.substring(searchname.length,singelcookie.length);
  }
  return null;
}

if(document.cookie){
    if(readCookie("width") == null || readCookie("height") == null){
        setCookie("width",screen.width,1);
        setCookie("height",screen.height,1);
        //location.reload();
    }
}else{
    setCookie("width",screen.width,1);
    setCookie("height",screen.height,1);
    //location.reload();
}

function loadPage() {
	$('hidepage').style.display='none';
}

