var applicationPath='/iCoke/';

var zoneDecorate="Scripts/Cuttle/decorator/img/loading.gif";

function doAjaxRequest(url, refreshZone){
	var aForm;
	var appID;
	var appCallBack;
	new sendRequest(url, aForm, appID, appCallBack, refreshZone);
	//location.href=location.href+"#"+url;
	//alert(location.href);
	//alert(location.href);
	//alert(location.pathname);

}
function doAjaxFormRequest(url, aForm, refreshZone){
	var appID;
	var appCallBack;
	new sendRequest(url, aForm, appID, appCallBack, refreshZone);
}

function doDelayRequest(url, delaySec){
	method="delayRequest('"+url+"')";
	//alert(method);
	setTimeout(method,delaySec);
}

function doDelayRequestZone(url, delaySec, refreshZone){
	method="doAjaxRequest('"+url+"','"+refreshZone+"')";
	//alert(method);
	setTimeout(method,delaySec);
}

function delayRequest(url){
	//alert(url);
	doAjaxRequest(url);
}
function divBlock(DivRef, IfrRef){
    DivRef.style.display = "block";
    IfrRef.style.width = DivRef.offsetWidth;
    IfrRef.style.height = DivRef.offsetHeight;
    IfrRef.style.top = DivRef.style.top;
    IfrRef.style.left = DivRef.style.left;
    IfrRef.style.zIndex = DivRef.style.zIndex - 1;
    IfrRef.style.display = "block";
}	
/**
 * XMLHttpRequest.js
 */ 
function DataSource(){
	this.maxReqSize=10;
	this.maxReqIdleTime=5000;
}

DataSource.prototype.getInstance=function(){
					//TODO:check timeout
					
    			var req=this.getReqFromPool();
    			
    			return req;	
};
DataSource.prototype.getReqFromPool=function(){
    		if(pool!=null && pool.length>0){
    			
	        for (var i = 0; i < pool.length; i ++)
	        {
	            if (pool[i].readyState == 0 || pool[i].readyState == 4)
	            {
	            		//document.getElementById('iamWinner').innerHTML+=''+i;
	                return pool[i];
	            }
	        }
        
      	}else{

      		for(i=0;i<this.maxReqSize;i++){
      			pool[i]=createXMLReq();
      		}

      		return pool[0];
      	}	
};
var pool=new Array();
var dataSource=new DataSource();

function createXMLReq(){
		var objXMLHttp=null;
    if (window.XMLHttpRequest){
        objXMLHttp = new XMLHttpRequest();

    }else{
        MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
        for(var n = 0; n < MSXML.length; n ++){
            try{
                objXMLHttp = new ActiveXObject(MSXML[n]);
                break;
            }catch(e){
            	
            }
        }
     }          

    if (objXMLHttp.readyState == null){
        objXMLHttp.readyState = 0;

        objXMLHttp.addEventListener("load", function (){
                objXMLHttp.readyState = 4;

                if (typeof objXMLHttp.onreadystatechange == "function"){
                    objXMLHttp.onreadystatechange();
                }
        },  false);
    }

		
    return objXMLHttp;
}

function sendRequest(url, form, appID, callback, refreshZone){

	if(applicationPath){
		urlPrefix=applicationPath;
	}
	showLoadingMessage('', appID);

	var objXMLHttp=dataSource.getInstance();


		try{
			var method=(form!=null && form!='')?'post':'get';

			var postData='';
			if(method=='get'){
				if (url.indexOf("?") > 0){
						url += "&randnum=" + Math.random();
						url+="&ajaxRequest=true";
				}else{
					url += "?randnum=" + Math.random();
					url+="&ajaxRequest=true";
				}
			}else{
				//alert(form);
				//alert(document.forms[form]);
				//document.getElemenetsByTagName(form);
				postData=preparePostData(document.forms[form]);
				
				postData="?randnum="+Math.random()+postData;
			}
			//urlPrefix='';
			//alert(urlPrefix+url);
			//alert(urlPrefix);
			//alert(url);
      		objXMLHttp.open(method, urlPrefix+url, true);

			objXMLHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			objXMLHttp.send(postData);
              

			objXMLHttp.onreadystatechange = function (){
				var state;
				var _status;

				if(objXMLHttp){

					state=objXMLHttp.readyState;
					if(state >= 4)
					_status=objXMLHttp.status;   			
													
				}							           
				if(state && _status)	
				if (state == 4 && (_status == 200 || _status == 304)){

					if(callback && callback!=''){
						callback(objXMLHttp, refreshZone, appID);
						hideLoadingMessage(appID, _status);
					}else{
						defaultCallback(objXMLHttp, refreshZone, appID);
						hideLoadingMessage(appID, _status);
					}
				}else if(state == 4){

						hideLoadingMessage(appID, _status);
				}else{
						
						showLoadingMessage(state, appID);
				}
			}
		}catch(e){
			alert(e);
		}
	
}
function forDebug(refreshZone){
	if(document.getElementById(refreshZone+"_wrapLine")){
		document.getElementById(refreshZone+"_wrapLine").style.cssText='width:100%; z-index:9999; border-color:gray;padding:2px; border-left-width:1px; border-right-width:1px;border-top-width:1px;border-bottom-width:1px; border-style: dotted';
	}
	if(document.getElementById(refreshZone+"_wrapTitle")){
		document.getElementById(refreshZone+"_wrapTitle").style.cssText='background-color:gray';
	}		
	if(document.getElementById(refreshZone+"_inLine")){
		document.getElementById(refreshZone+"_inLine").style.cssText='width:100%; z-index:9999; border-color:gray;padding:2px; border-left-width:1px; border-right-width:1px;border-top-width:1px;border-bottom-width:1px; border-style: dotted';
	}

	if(document.getElementById(refreshZone+"_inTitle")){
		document.getElementById(refreshZone+"_inTitle").style.cssText='background-color:gray';
	}
}
function recover(refreshZone){
	if(document.getElementById(refreshZone+"_wrapLine")){
		document.getElementById(refreshZone+"_wrapLine").style.cssText='width:100%; z-index:9999; border-color:red;padding:2px; border-left-width:1px; border-right-width:1px;border-top-width:1px;border-bottom-width:1px; border-style: dotted';
	}
	if(document.getElementById(refreshZone+"_wrapTitle")){
		document.getElementById(refreshZone+"_wrapTitle").style.cssText='background-color:red';
	}	
	if(document.getElementById(refreshZone+"_inLine")){
		document.getElementById(refreshZone+"_inLine").style.cssText='width:100%; z-index:9999; border-color:#CCCCCC;padding:2px; border-left-width:1px; border-right-width:1px;border-top-width:1px;border-bottom-width:1px; border-style: dotted';
	}
	if(document.getElementById(refreshZone+"_inTitle")){
		document.getElementById(refreshZone+"_inTitle").style.cssText='background-color:#CCCCCC';
	}
}
var applicationList=new ArrayList();
function defaultCallback(xmlHttpReq, refreshZone, appID){
	//alert(xmlHttpReq.responseText);
	var doc=xmlHttpReq.responseXML;		
	var contents=doc.getElementsByTagName('block');
	var scripts=doc.getElementsByTagName("script");
	for(i=0;i<contents.length;i++){

		var decoratorType=contents[i].getAttribute('decorator');
		var delay=contents[i].getAttribute("delay");
		var winTheme=contents[i].getAttribute("theme")!=''?contents[i].getAttribute("theme"):"default";
		var winTitle=contents[i].getAttribute("title")!=''?contents[i].getAttribute("title"):"Title";
		var winHeight=contents[i].getAttribute("height")!=''?contents[i].getAttribute("height"):300;
		var winWidth=contents[i].getAttribute("width")!=''?contents[i].getAttribute("width"):400;
		var winTop=contents[i].getAttribute("top")!=''?contents[i].getAttribute("top"):100;
		var winLeft=contents[i].getAttribute("left")!=''?contents[i].getAttribute("left"):100;
		//for disableAjaxForward
		var forward=contents[i].getAttribute("forward");
		if(refreshZone && refreshZone!=''){
			curTagID=refreshZone;
		}else{	
			curTagID=contents[i].getAttribute('id');
		}
		
		aMethod="forDebug('"+curTagID+"')";
		setTimeout(aMethod, 1000);
		anotherMethod="recover('"+curTagID+"')";
		setTimeout(anotherMethod, 2000);
		
		//forDebug(curTagID);
		if(forward=='true'){
			for(j=0;j<contents[i].childNodes.length;j++){	
				if(contents[i].childNodes[j].data && contents[i].childNodes[j].data!=''){
					var URL=contents[i].childNodes[j].data.split(':=')[1];
					if(URL)
					location.href=URL;							
				}
			}
		}else if(delay=='true'){
			for(j=0;j<contents[i].childNodes.length;j++){	
				if(contents[i].childNodes[j].data && contents[i].childNodes[j].data!=''){
					//alert(contents[i].childNodes[j].data.split(','));
					var parameterPairs=contents[i].childNodes[j].data.split(',');
					var URL=parameterPairs[0].split(':=')[1];
					var delaySec=1;
					if(parameterPairs[1])
					delaySec=parameterPairs[1].split(':=')[1];
					if(URL)
					doDelayRequest(URL, delaySec);								
				}
			}	
		}else{
			if(document.getElementById(curTagID)){
				if(decoratorType!='' && decoratorType=='application'){
				}else{
					document.getElementById(curTagID).innerHTML='';
				}
				
				var contentHTML='';
				for(j=0;j<contents[i].childNodes.length;j++){	
					if(contents[i].childNodes[j].data && contents[i].childNodes[j].data.length>0){
						contentHTML+=contents[i].childNodes[j].data;
					}
				}		

				showContent(decoratorType, contentHTML, curTagID, winTheme, winTitle, winWidth, winHeight, winTop, winLeft);
			}	
		}
	}
	
	if(scripts){		
		for(i=0;i<scripts.length;i++){		
			var subScripts = scripts[i];
			for(j=0;j<subScripts.childNodes.length;j++){		     	
				if(subScripts.childNodes[j].data && subScripts.childNodes[j].data!='')
					cuttle.eval(subScripts.childNodes[j].data);
			}
		}
	}

}
function showContent(decoratorType, contentHTML, curTagID, winTheme, winTitle, winWidth, winHeight, winTop, winLeft){

				if(decoratorType!='' && decoratorType=='application'){
					var contentWin;
					var isExist=false;
					for(k=0;k<applicationList.size();k++){
						contentWin=applicationList.get(k);
						if(contentWin.getId()==curTagID+"_win"){
							isExist=true;
							break;
						}
					}
					if(isExist){
						contentWin.setHTMLContent(contentHTML);
						scriptTags=document.getElementById(curTagID+"_win").getElementsByTagName("script");
						for(k=0;k<scriptTags.length;k++){
							cuttle.eval(scriptTags[k].innerHTML);
						}
						
						contentWin.setTitle(winTitle);
						contentWin.toFront();
						contentWin.show();
					}else{
						contentWin=new Window(curTagID+"_win", {className: winTheme, title: winTitle, width:winWidth, height:winHeight, top:winTop, left:winLeft});
						contentWin.setHTMLContent(contentHTML);
						scriptTags=document.getElementById(curTagID+"_win").getElementsByTagName("script");
						for(k=0;k<scriptTags.length;k++){
							cuttle.eval(scriptTags[k].innerHTML);
						}
						contentWin.toFront();
						contentWin.show();
						applicationList.add(contentWin);
					}
				}else{
					document.getElementById(curTagID).innerHTML=contentHTML;
					scriptTags=document.getElementById(curTagID).getElementsByTagName("script");
					
					for(k=0;k<scriptTags.length;k++){
					
						cuttle.eval(scriptTags[k].innerHTML);
					}
				}
}

function hideLoadingMessage(appID, status){
	if(status==200 || status==304){
		if(hideMessage)hideMessage(appID);
	}else{
		//TODO
		//alert(status);
		alert(appMessageSystemBusy);
	}
}

function preparePostData(form) {
    
    var result = "";
    for (var i = 0; i < form.elements.length; i++) {
        var el = form.elements[i];
        if (el.tagName.toLowerCase() == "select") {
            for (var j = 0; j < el.options.length; j++) {
                var op = el.options[j];
                if (op.selected)
                    result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(op.value);
            }
        } else if (el.tagName.toLowerCase() == "textarea") {
            result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value);
        } else if (el.tagName.toLowerCase() == "input") {
            if (el.type.toLowerCase() == "checkbox" || el.type.toLowerCase() == "radio") {
                if (el.checked)
                    result += "&" + encodeURIComponent(el.name) + "=" + encodeURIComponent(el.value);
            }else if(el.type.toLowerCase()=="text" || el.type.toLowerCase()=='hidden'){
            	result+="&"+encodeURIComponent(el.name)+"="+encodeURIComponent(el.value);
            }else{
            	result+="&"+encodeURIComponent(el.name)+"="+encodeURIComponent(el.value);
            }
        }
    }
    result+="&ajaxRequest=true";
    return result;
}
var cuttle={}    
cuttle.eval=function(code){
if(!!(window.attachEvent && !window.opera)){
 execScript(code); 
}else{
 window.eval(code);
}
}

/**
 *arrayList
 */
var applicationList=new ArrayList();
function ArrayList(){
 this.buffer=new Array();
 var args=ArrayList.arguments;
 if(args.length>0) this.buffer=args[0];
 this.length=this.buffer.length;

 this.hashCode=hashCode;
 function hashCode(){
  var h=0;
  for(var i=0;i<this.lengh;i++)
   h+=this.buffer[i].hashCode();
  return h;
 }
 
 this.size=size;
 function size(){
  return this.length;
 }

 
 this.clear=clear;
 function clear(){
  this.length=0;
 }

 
 this.isEmpty=isEmpty;
 function isEmpty(){
  return this.length==0;
 }
 
 
 this.get=get;
 function get(index){
  if(index>=0 && index<this.length)
   return this.buffer[index];
  return null;
 }

 
 this.remove=remove;
 function remove(param){
  var index=0;
  
  if(isNaN(param)){
   index=this.indexOf(param);
  }
  else index=param;
  
  
  if(index>=0 && index<this.length){
   for(var i=index;i<this.length-1;i++)
    this.buffer[i]=this.buffer[i+1];
   this.length-=1;
   return true;
  }
  else return false;
 }
 
 this.add=add;
 function add(){
  var args=add.arguments;
  if(args.length==1){
   this.buffer[this.length++]=args[0];
   return true;
  }
  else if(args.length==2){
   var index=args[0];
   var obj=args[1];
   if(index>=0 && index<=this.length){
    for(var i=this.length;i>index;i--)
     this.buffer[i]=this.buffer[i-1];
     this.buffer[i]=obj;
    this.length+=1;
    return true;
   }
  }
  return false;
 }

 this.contains=contains;
 function contains(obj){
  return this.indexOf(obj)!=-1;
 }

 this.equals=equals;
 function equals(obj){
  if(this.size()!=obj.size()) return false;
  for(var i=0;i<this.length;i++){
   if(!obj.contains(this.buffer[i])) return false;
  }
  return true;
 }
 
 
 this.retainAll=retainAll;
 function retainAll(list){
  for(var i=this.length-1;i>=0;i--){
   if(!list.contains(this.buffer[i])){
    this.remove(i);
   }
  }
 }
 
 this.set=set;
 function set(index,obj){
  if(index>=0 && index<this.length){
   temp=this.buffer[index];
   this.buffer[index]=obj;
   return temp;
  }
 }
 
}

