/***************************\
Contains:
	Extension:	Claim.isFunction	- assertions for functions
	Extension:	Element.setText		- sets Value/innerHTML/textContent by element type
	Function:	Serialize(obj)		- Serializable to JSON
    Extension:  Function.insert     - insert a line into the function  
    Function:   ask()               - a debug utility
\***************************/
//-----------------------------------------------------------------
Object.extend( Class, {
  isInheritable: function(parentClassName){
    if (!parentClassName) return false;

    var parentClass;
    switch(typeof(parentClassName)){
        case "function":
            parentClass = parentClassName;
            parentClassName = parentClass.toString();
            return (  !parantClassName.match(/function\(/gi)
                   && window[parentClassName] != null
                   && window[parentClassName] == eval(parentClassName)
                   );

        case "string":
            try{
                parentClass = eval(parentClassName);
            }catch(ex){return false;} 
            return  (   parentClass != null 
                    &&  typeof(parentClass) == 'function'
                     );
        default:
            return false;
    }   
  }
  ,createSubclass: function(parentClassName){
    var parentClass;

    if(!Class.isInheritable(parentClassName))
        throw "Illegal parameter for Class.createSubclass:" + parentClassName + ". Class.create accepts a valid class-name as string, or a reference to the class if the class has a static override for the toString(), providing its class name as string.";

    if(typeof(parentClassName) == 'string'){
        parentClass = eval(parentClassName);
    }else{
        parentClass = parentClass;
        parentClassName = parentClass.toString();
    }

    Claim.isString(parentClassName,"Class.createSubclass(parentClassName)");
    Claim.check( typeof(parentClass) == 'function' &&
                 typeof(parentClass.prototype.initialize) == 'function'  
               , "typeof(eval(parentClassName).prototype.initialize) == 'function'"
               , "Class.createSubclass(parentClassName): parentClassName is not inheritable using the createSubclass mechanizm." );

    var f = new Function(parentClassName + ".prototype.initialize.apply(this, arguments);\n" 
                         + "this.initialize.apply(this, arguments)" );

    return f;
  }
});
//-----------------------------------------------------------------
Object.extend(Claim, {
	isFunction: function(object, comment)
	{{
        Claim.check(typeof(object) == 'function',
                                "isFunction(" + Claim.valueType(object) + ")",
                             comment)
	}}
});
//-----------------------------------------------------------------
Object.extend(Element, {
    log: new Log4Js.Logger("Element")
	,setText: function(e,sText){
		var tag = e.tagName.toUpperCase();
		switch(tag){
			case "INPUT":
			case "TEXTAREA":
				e.value = sText;
				break;
			case "SELECT":
				//TODO: - decide what to do if the sText doesnt match any value of the select element
				e.value = sText;
				break;
			default:/*DIV, SPAN, TD, A, H1-H5, and all the rest*/
				try{
					e.innerHTML = sText;
				}catch(ex){
					try{
						if(typeof e.innerText == 'undefined')
							e.textContent = sText;
						else
							e.innerText = sText;
					}catch(ex){
					    this.log.error("Element.setText: failed to set to element the text: " + sText);
					}
				}
		}
	}
});
//-----------------------------------------------------------------
Serialize = function(obj){
	if (!obj) return 'null';

	var str = '';
	var psik = '';
	for (each in obj){
		str += psik; psik = ","; //adds a comma from 2nd time only
		str += each +":"
		switch(typeof(obj[each])){
			case 'function': 
				break;
			case 'object':
				str += Serialize(obj[each]);
				break;
			case 'string':
			    str += '"' + obj[each].replace(/\"/,"\"") + '"';
			    break;
			default:
				str += obj[each];
		} 
	}
	return "{" + str + "}";
}
//-----------------------------------------------------------------
Function.prototype.insert = function(sCodeLine){
	var a = this.toString().split("{");
	a[1] = "\n\t" + sCodeLine + a[1];
	return (eval("a = " + a.join("{")));
}
//-----------------------------------------------------------------
Glossary =	{ _terms:	{}
			, addPair:	function addPair(key, value){ this._terms[key] = value; }
			, term:		function term(key){ return this._terms[key]; }
			};
//TODO: replace the term identifiers with term GUID
Glossary.addPair('{JAST_REQUEST_TIMEOUT_DEF_MSG}','Problems connecting to the server.');
Glossary.addPair('{JAST_REQUEST_REFUSED_DEF_MSG}','Server failes the request');
//-----------------------------------------------------------------
function ask(){
	var s = '';
	while(s!= "STOP"){
		s = prompt('To close - enter "STOP"',s);
		if (s == "STOP") return;
		alert(eval(s));
	}
}

function CreateHiddenInput(sName, sValue)
{
	var input = document.createElement("input");
	input.setAttribute("type", "hidden");
	input.setAttribute("name", sName);
	input.setAttribute("value", sValue);
	return input;
}

//This method facilitates posting data without refreshing the current window.
function PostIframeRequest(form, callback) { 
    
    var parts = window.location.hostname.split(".");
    document.domain = parts[parts.length - 2] + "." + parts[parts.length - 1];
    var remotingDiv = document.createElement("div"); 
    document.body.appendChild(remotingDiv); 
    remotingDiv.id = "remotingDiv"; 
    remotingDiv.innerHTML = "<iframe name='remotingFrame' id='remotingFrame' style='border:0;width:0;height:0;'></iframe>"; 
    remotingDiv.iframe = document.getElementById('remotingFrame'); 
    remotingDiv.form = form; 
    remotingDiv.form.setAttribute('target', 'remotingFrame'); 
    remotingDiv.form.target = 'remotingFrame'; 
    remotingDiv.appendChild(remotingDiv.form); 
    remotingDiv.callback = callback; 
    remotingDiv.form.submit(); 
}

function InvokeCallback(returnStatus){
    try
    {
        document.getElementById('remotingDiv').callback(returnStatus);
    }
    catch(ex){}
}

//=== Class UserUtils
if(!window.UA) 	UA = {};
UA.UserUtils = Class.create();
UA.UserUtils.prototype.Callback;

// UA Login and Initialization
// numOfTicks must be a positive integer
// tickInterval must be positive (milliseconds)
// paramsList must be in form of "Param1:value1,Param2:value2".
UA.UserUtils.DoLogIn = function(tickInterval, numOfTicks, callback, paramsList){
    UA.UserUtils.prototype.Callback = callback;
	UserLogIn();   //This method should be declared by each channel, and its path will be kept in the channel propeties table. 
    var funcStr = "UA.UserUtils.polling(" + tickInterval + "," + numOfTicks + ",'" + paramsList +"')";
    setTimeout(funcStr, tickInterval);
}

UA.UserUtils.DoLogOut = function(callback){
    UserLogOut();
}

UA.UserUtils.DoRegister = function(callback){
    UserRegister();
}

UA.UserUtils.DoEndGameFlow = function(launcherObjects){
    EndGameFlow(launcherObjects);
}


UA.UserUtils.polling = function(tickInterval, numOfTicks, paramsList){
    if(numOfTicks == 0)
    {
        //tell the caller that the polling ended with no success
        UA.UserUtils.prototype.Callback("User is still Logged off.");
        return;
    }

    if(!UA.User.prototype.IsLoggedOn())
    {
        numOfTicks = numOfTicks - 1;
        var funcStr = "UA.UserUtils.polling(" + tickInterval + "," + numOfTicks + ",'" + paramsList +"')";
        setTimeout(funcStr, tickInterval);
        return;
    }
    //Perform InitializeUA()
    UA.UserUtils.InitializeUA(UA.UserUtils.prototype.Callback, paramsList);    
}

//paramsList ->In order to send parameters use this syntax: paramsList = "Param1:value1,Param2:value2";
UA.UserUtils.InitializeUA = function(callback, paramsList){
    var methodsArr = new Array( UA.User.Methods.ISSUBSCRIBED,
                                UA.User.Methods.ISAUTHORIZED, 
                                UA.User.Methods.GETUSER, 
                                UA.User.Methods.HASFREETRIAL,
                                UA.User.Methods.GET_OBERON_CLIENT_USERID, 
                                UA.User.Methods.GET_PARTNER_PROGRAM_ID);
    UA.UserUtils.prototype.Callback = callback;
    UA.User.prototype.GetData(methodsArr, paramsList, InitializeUASuccess, InitializeUAFail, InitializeUATimeout);
}

function InitializeUASuccess(request){
    UA.StaticUser.prototype.IsSubscribed = (request.IsSubscribed.Data.isSubscribed == "True") ? true : false;
    UA.StaticUser.prototype.IsAuthorized = request.IsAuthorized.Data.isAuthorized;
    UA.StaticUser.prototype.HasFreeTrial = (request.HasFreeTrial.Data.hasFreeTrial == "True") ? true : false;
    UA.StaticUser.prototype.OberonClientUserId = request.GetOberonClientUserId.Data.userGuid;
    UA.StaticUser.prototype.PartnerProgramId = request.GetPartnerProgramId.Data.ProgramId;
    UA.StaticUser.prototype.Nickname = request.GetBasicUserDetails.Data.Nickname;
    UA.StaticUser.prototype.AvatarURL = request.GetBasicUserDetails.Data.AvatarURL;
    UA.StaticUser.prototype.AvatarName = request.GetBasicUserDetails.Data.AvatarName;
    UA.UserUtils.prototype.Callback(true);
}

function InitializeUAFail(request){
    UA.UserUtils.prototype.Callback(request.Status);
}

function InitializeUATimeout(request){
    UA.UserUtils.prototype.Callback("Timeout");
}
//=== Class UserUtils



