//var STATIC_CONTENT_HOST		= ((location.hostname.indexOf("azbuz.ekolay.net")>=0) || (location.hostname.indexOf("videoazbuz.ekolay.net")>=0))? "http://s.azbuz.com/" : "/";
var STATIC_CONTENT_HOST		= "http://s.azbuz.com/";
var VIDEO_HOST		= (location.hostname.indexOf("azbuz.com")>=0) || (location.hostname.indexOf("video.azbuz.com")>=0)   ? "http://213.243.33.236/" : "";
var ID_PREFIX_MULTIPLIER	= 1000000000000000;
var ID_PREFIX_ARTICLE		= 5;

var xmlHttp; 
var requestURL = '';
var contentArea = 'mua';
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0; 
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
var is_opera = ((navigator.userAgent.indexOf("Opera 6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
//netscape, safari, mozilla behave the same??? 
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0; 
var pip = false;

function show_data(strName, strContentArea){ 
	//Append the name to search for to the requestURL 
	var url = requestURL + strName; 
	contentArea = strContentArea;

	//Create the xmlHttp object to use in the request 
	//stateChangeHandler will fire when the state has changed, i.e. data is received back 
	//This is non-blocking (asynchronous)
	xmlHttp = GetXmlHttpObject(stateChangeHandler);
	putLoading(); //put loading thing to object

	//Send the xmlHttp get to the specified url
	xmlHttp_Get(xmlHttp, url);
} 

//stateChangeHandler will fire when the state has changed, i.e. data is received back 
// This is non-blocking (asynchronous) 
function stateChangeHandler(){ 
	//readyState of 4 or 'complete' represents that data has been returned 
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){ 
		//Gather the results from the callback 
		var str = "";
		
		try{str = xmlHttp.responseText;}
		catch(e){}

		//Populate the innerHTML of the div with the results 
		if(str.length>0){
			if(document.getElementById(contentArea)){
				removeLoading();
				document.getElementById(contentArea).innerHTML = str;
			}else{
				alert("Could't find the area to put the data.");
				removeLoading();
			}
		}else{
			removeLoading();
		}
	} 
} 

// XMLHttp send GET request 
function xmlHttp_Get(xmlhttp, url) { 
	xmlhttp.open('GET', url, true); 
	xmlhttp.send(null); 
} 

function GetXmlHttpObject(handler) { 
	var objXmlHttp = null;    //Holds the local xmlHTTP object instance 

	//Depending on the browser, try to create the xmlHttp object 
	if (is_ie){ 
		//The object to create depends on version of IE 
		//If it isn't ie5, then default to the Msxml2.XMLHTTP object 
		var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 
         
		//Attempt to create the object 
		try{ 
			objXmlHttp = new ActiveXObject(strObjName); 
			objXmlHttp.onreadystatechange = handler; 
		} 
		catch(e){ 
		//Object creation errored 
			alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled'); 
			return; 
		} 
	} 
	else if (is_opera){ 
		//Opera has some issues with xmlHttp object functionality 
		alert('Opera detected. The page may not behave as expected.'); 
		return; 
	} 
	else{ 
		// Mozilla | Netscape | Safari 
		objXmlHttp = new XMLHttpRequest(); 
		objXmlHttp.onload = handler; 
		objXmlHttp.onerror = handler; 
	} 
     
	//Return the instantiated object 
	return objXmlHttp; 
}

function putLoading(){
	if(document.getElementById(contentArea)){
		document.getElementById(contentArea).innerHTML = "Yükleniyor...";
		document.getElementById(contentArea).style.cursor = "wait";
	}
}

function removeLoading(){
	if(document.getElementById(contentArea)){
		document.getElementById(contentArea).innerHTML = "";
		document.getElementById(contentArea).style.cursor = "default";
	}
}

var arrProcessHistory = new Array(0);
function oyXMLRPCProvider(showLoading, doNOTrequestTwice){
	var url = null;	
	var msg = null;
	var req = null;

	var oThis = this;

	this.createPacket = null;

	//get the caller function details
	myCallerName = oyXMLRPCProvider.caller.toString().match(/function (\w*)/)[1];
	myCallerArgCount = oyXMLRPCProvider.caller.arguments.callee.arguments.length;
	var strArguments = "";


	if(myCallerArgCount>0){
		for(var argCount = 0; argCount < myCallerArgCount; argCount++){
			strArguments += "#SA#" + oyXMLRPCProvider.caller.arguments.callee.arguments[argCount] + "#SA#";
			if(argCount+1<myCallerArgCount){strArguments += ",";}
		}
	}
	var strFunction = myCallerName + "(" + strArguments + ")";

	//pespese ayni requestlerin gonderilmesini engellemek adina boyle bisi yapildi.
	//eger ki pespese ayni isi yapmasi gereken methodlarimzi war veya olacak ise bu fonksiyon showLoading gibi bir parametre daha alabilir ve duruma gore doTheJob parametresini true'ya cekebilir.
	//push caller and arguments to my array if necessary

	var doTheJob = true;
	if(doNOTrequestTwice!=null && doNOTrequestTwice==true && arrProcessHistory[arrProcessHistory.length - 1]==strFunction){
		doTheJob = false;
	}else{
		arrProcessHistory.push(strFunction);
	}
	
	
	//aşagıdaki satır java script hatası veriyor bazı yerlerde.Kaldırdım oyuzden.
	//dbg("arrProcessHistory:"+arrProcessHistory);
	// internal callback function for the browser; it is called when a state of a request object changes
	var internalRequestComplete = function() {
		var STATE_COMPLETED = 4;
		var STATUS_200 = 200;
		if (req.readyState == STATE_COMPLETED) {
			if (req.status == STATUS_200) {
				if(showLoading==null || showLoading){loading("none");}
				if(oThis.onComplete){
					respText = req.responseText;

					if(respText!=null && respText.length>0){
						try{
							reader = new CmdReader(respText);							
							id = reader.getID();
							method = reader.getMethod();							
							if(id!=null && method!=null){
								if(id=="0"){
									dbg("XMLRPCProvider error : Server returned an error!!!");
								}else if(id=="-1"){
									dbg(strFunction);
									displayLogin(strFunction);
									dbg("XMLRPCProvider error : Session died!!!");
								}else if(id=="-2"){
									dbg(strFunction);
									displayLogin(strFunction, "Bu işlemi yapabilmek için Admin veya Site Sahibi rollerinden en az birine sahip olmalısınız.");
								}else if(id=="-3"){
									dbg(strFunction);
									alertUser("Hata","Bu işlemi yapabilmek için Site Sahibi olmalısınız.");
								}else{
									oThis.onComplete(req.responseText);
								}
							}
						}catch(e){
							if(e.description == null){
								dbg("XMLRPCProvider error<br>CallerName : " + myCallerName + "<br>Err : " + e.message + "<br>And the responseText iz : " + respText);
							}else{
								dbg("XMLRPCProvider error<br>CallerName : " + myCallerName + "<br>Err : " + e.description + "<br>And the responseText iz : " + respText);
							}
						}
					}else{
						dbg("XMLRPCProvider error : responseText is null!!!");
					}
				}				 
			} 
		}
	}	

	//  call this function to submit new request
	this.submit = function(_url){
		if(doTheJob){
			if(showLoading==null || showLoading){loading("");}
			url = _url;	
			
			msg = "";
			if(oThis.createPacket) {
				msg = oThis.createPacket();
			}
			
		    if (window.XMLHttpRequest) {
		    	// branch for native XMLHttpRequest object
		        req = new XMLHttpRequest();
		        req.onreadystatechange = internalRequestComplete;
		        req.open("PUT", url, true);
	        	req.send(msg);	
		    } else { 
		    	// branch for IE/Windows ActiveX version
		    	if (window.ActiveXObject) {	    		
			        req = new ActiveXObject("Microsoft.XMLHTTP");
			        if (req) {
			            req.onreadystatechange = internalRequestComplete;
			            req.open("PUT", url, true);
				    	req.setrequestheader("Pragma","no-cache");
			   	    	req.setrequestheader("Cache-control","no-cache");
			        	req.send(msg);	
			        } 
			    } 
		    }
		}else{
			dbg("doTheJob iz false");
		}
	}
	// user can override this;  this function is called when response is received without errors
	this.onComplete = function(responseText){
	}
}

function loading(strDisplayValue){
	try{document.getElementById("loading").style.display = strDisplayValue;}
	catch(e){}
}

function dbg(debugStr){
		if(document.getElementById("debug")){
			document.getElementById("debug").innerHTML = "<pre>" + debugStr + "</pre>" + document.getElementById("debug").innerHTML;
		}
}

function flipRegular(elementId){

	try{
		var myElement = document.getElementById(elementId);

		if(myElement){
			if(myElement.style.display == ""){
				myElement.style.display = "none";
			}else{
				myElement.style.display = "";
					var w = myElement.style.width;
					var h = myElement.style.height;
					w = w.replace("px","");
					h = h.replace("px","");
					myElement.style.left=getCenterXCoordinateWindow(w);
					myElement.screenX = getCenterXCoordinateWindow(w);
					myElement.style.top =getCenterYCoordinateWindow(h)+200;
					myElement.screenY = getCenterYCoordinateWindow(h)+200;
			}
		}
	}
	catch(e){}
}

function getCenterXCoordinateWindow (x){
		
		var width = document.body.scrollLeft;
   		return width+(document.body.clientWidth-x)/2;


}
function getCenterYCoordinateWindow (y){
	
	var height = document.body.scrollTop;
	return height+(document.body.clientHeight-y)/2;

}


function setElementPositionByMouse(elementId){
	if(document.getElementById(elementId)){
		myElement = document.getElementById(elementId);

		clientWidth = document.body.clientWidth;
		clientHeight = document.body.clientHeight;
		elementsWidth = (myElement.width!=undefined) ? parseInt(myElement.width) : parseInt(myElement.style.width);
		elementsHeight = (myElement.height!=undefined) ? parseInt(myElement.height) : parseInt(myElement.style.height);

		//alert("clientWidth:"+clientWidth+"\nclientHeight:"+clientHeight+"\nelementsWidth:"+elementsWidth+"\nelementsHeight:"+elementsHeight+"\nmouseX:"+mouseX+"\nmouseY:"+mouseY);

		//myElement.style.left = (mouseX + 20) + "px";
		//myElement.style.top = mouseY + "px";
new Effect.Move (myElement,{ x: (mouseX + 20), y: mouseY, mode: 'absolute'});
new Effect.ScrollTo(myElement, {offset: -24});
		/*
		if(clientWidth > 0 && elementsWidth > 0){
			myElement.style.left = ((mouseX + elementsWidth > clientWidth) ? clientWidth - elementsWidth : mouseX + 20) + "px";
			myElement.style.top = ((mouseY + elementsHeight > clientHeight) ? clientHeight - elementsHeight : mouseY) + "px";
		}else{
			myElement.style.left = (mouseX + 20) + "px";
			myElement.style.top = mouseY + "px";
		}
		*/
	}
}

function displayLogin(funcToEval, strMessage,refreshFlag){
    
	Modalbox.show('Sisteme Giriş', '' , {width: 400,height:200,params:'Login'});
	return false;
	document.getElementById("email").focus();

}
function displayLoginVideo(){
	Modalbox.show('Sisteme Giriş', '' , {width: 400,height: 200,params:'videoLogin'});
	return false;

}

function login(funcToEval,refreshFlag){   
	strEmail = document.getElementById("email").value;
	strPassword = document.getElementById("password").value;
	var myCreatePacket = function(){
		writer = new CmdWriter(2);
		writer.appendStr(strEmail);
		writer.appendStr(strPassword);
		if(document.getElementById("rememberLogin") != null && document.getElementById("rememberLogin").checked==true){
			writer.appendStr("true");
		}else{
			writer.appendStr("false");		
		}
		writer.endOfObject();
		dbg(writer.Buffer);
		return writer.Buffer;
	}

	var myOnComplete = function(responseText){
		//dbg("login response : " + responseText);
		reader = new CmdReader(responseText);
		reply = reader.getStr();			
		if(reply=="true"){
		    
			loggedInUserId = reader.getStr();
			userNickname = reader.getStr();
			userGender = reader.getStr();
			funcToEval = replaceAll(funcToEval, "#SA#", "'")
			eval(funcToEval);
			if(refreshFlag=="true"){
				if(Modalbox != null)
					Modalbox.hide(); 
				document.location.reload(false);
			}
		}else{					
			document.getElementById('errorMessageArea').innerHTML = "Hatalı Giriş";
		}
	}

	var provider = new oyXMLRPCProvider();
	provider.createPacket = myCreatePacket;
	provider.onComplete = myOnComplete;
	provider.submit("/user.ajax");
	return false;
}

function loadXMLDoc(fname)
{
	var xmlDoc;
	// code for IE
	if (window.ActiveXObject){
	  xmlDoc=new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
	}
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument){
	  xmlDoc=document.implementation.createDocument("","",null);
	}
	else{
	  alert('Your browser cannot handle this script');
	}
	xmlDoc.async=false;
	xmlDoc.load(fname);
	return(xmlDoc);
}
function transformXmlXsl(xmlUrl,xslUrl,xslt_parameters,xslt_parameters_names){
	xml=loadXMLDoc(xmlUrl);
	xsl=loadXMLDoc(xslUrl);
	var result;
	// code for IE
	if (window.ActiveXObject){
		objxsltTemplate = new ActiveXObject("MSXML2.XSLTemplate");
     	objxsltTemplate.stylesheet = xsl;
     	objxsltProcessor = objxsltTemplate.createProcessor();
     	objxsltProcessor.input = xml;     	
		if(xslt_parameters!=null){
			for(i=0;i<xslt_parameters_names.length ;i++){
				objxsltProcessor.addParameter(xslt_parameters_names[i], xslt_parameters[xslt_parameters_names[i]]);
			}
		}
 		objxsltProcessor.transform();
 		result=objxsltProcessor.output;
 		
 	}// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument){
        xsltProcessor=new XSLTProcessor();
        if(xslt_parameters!=null){
	        for(aKey in xslt_parameters){
				xsltProcessor.setParameter(null,aKey, xslt_parameters[aKey]);
			}
		}
	    xsltProcessor.importStylesheet(xsl);
	    result = xsltProcessor.transformToFragment(xml,document).childNodes[0].innerHTML;
 	}
 	return result;
}

