
//Initialization =======================

//create loading div
var divAppLoading = document.getElementById('divAppLoading');
//var arrOffset = appElementDocOffset(divAppLoading);
divAppLoading.style.left = 0;//-arrOffset[0];
divAppLoading.style.top = 0;//-arrOffset[1];

//Public Data Functions =======================

function appGetItem(listname, itemkey, asyncCallback){
    itemkey = itemkey + ''; //key is always string
    var url = 'request.jsp?cmd=getitem&appid=' + appId + '&listname=' + encodeURIComponent(listname) + '&itemkey=' + encodeURIComponent(appStringifyKey(itemkey));
    return appAjaxCall(url, asyncCallback);
}

function appGetList(listname, asyncCallback){
    var url = 'request.jsp?cmd=getlist&appid=' + appId + '&listname=' + encodeURIComponent(listname);
    return appAjaxCall(url, asyncCallback);
}

function appGetListMatches(listname, itemkey, asyncCallback){
    var url = 'request.jsp?cmd=matchlist&appid=' + appId + '&listname=' + encodeURIComponent(listname) + '&itemkey=' + encodeURIComponent(appStringifyKey(itemkey));
    return appAjaxCall(url, asyncCallback);
}

function appDeleteItem(listname, itemkey, asyncCallback){
    itemkey = itemkey + ''; //key is always string
    var url = 'request.jsp?cmd=deleteitem&appid=' + appId + '&listname=' + encodeURIComponent(listname) + '&itemkey=' + encodeURIComponent(appStringifyKey(itemkey));
    return appAjaxCall(url, asyncCallback);
}

function appSaveItem(listname, obj, asyncCallback){
    var itemkey;
    for(prop in obj){
            itemkey = eval('obj.'+prop) + '';
            break;		
    }
    itemkey = itemkey + ''; //key is always string
    if (itemkey=='') {
        alert('Object cannot be saved without a key value.');
        return;
    }
    eval('obj.' +prop+ '= itemkey'); //resave key
    var json = JSON.stringify(obj);
    itemkey = appStringifyKey(itemkey);
    var url = 'request.jsp?cmd=saveitem&appid=' + appId + '&listname=' + encodeURIComponent(listname) + '&itemkey=' + encodeURIComponent(itemkey) + '&json=' + encodeURIComponent(json);
    return appAjaxCall(url, asyncCallback);
}

//Public Helper Functions =======================

function appSortObjects(objs, prop, direction){
    direction = (direction==null) ? 1 : -1;
    var retObjs = objs;
    var keyi, obji, vali;
    var ordercount = 1;
    while (ordercount > 0){
        var arrKeys = [];
        for (key in retObjs) {
            arrKeys[arrKeys.length] = key;
        }
        ordercount = 0;
        for (var i=0; i<(arrKeys.length-1); i++){
            obji = eval('retObjs[arrKeys[i]]');
            vali = eval('obji.' + prop);
            if ( ((direction>0)&&(vali > eval('retObjs[arrKeys[i+1]].' + prop))) || ((direction<0)&&(vali < eval('retObjs[arrKeys[i+1]].' + prop))) )
                {
                ordercount ++;
                delete retObjs[arrKeys[i]];
		retObjs = eval('(' + JSON.stringify(retObjs) + ')'); //IE doesn't push-pop right
                retObjs[arrKeys[i]] = obji;
            }
        }
    }
    return retObjs;
}

function appRequireLogin(){
    if (appUserId==0) location.href = 'login.jsp?redirect=' + escape(location);
}

function appLoadYahooPipe(strPipeId, strCallBackFunctionName, objParams){
  var url = "http://pipes.yahoo.com/pipes/pipe.run?_id=" + strPipeId + "&_render=json&_callback=" + strCallBackFunctionName;
  for (key in objParams){
      url += "&" + key + "=" + escape(objParams[key]);
  }
  var script=document.createElement('script');
  script.src = url;
  script.type="text/javascript";
  document.getElementsByTagName('head')[0].appendChild(script);
}

function appGetEl(strId){
    return document.getElementById(strId);
}

function appStringify(obj){
    return JSON.stringify(obj);
}

function appCreateGuid(){
	var now = new Date(); 
	var guid = "";//now.getYear() + '-' + now.getMonth() + '-' + now.getDate() + '-' + now.getHours() + '-' + now.getMinutes() + '-';
	guid += Math.round(Math.random()*1000000000).toString(32);
	return guid;
}

function appGetUrl(url, callbackFunction){
	var xmlhttp = appGetXmlHttp();
	xmlhttp.onreadystatechange = function() {
		if((xmlhttp.readyState==4)) {
			eval(callbackFunction + '(xmlhttp.responseText)');
		}
	};
	xmlhttp.open("GET", url, true);
	xmlhttp.send(null);
}


//Private Supporting Functions=========================

function appShowLoading(){
    document.getElementById('divAppLoading').style.visibility = "visible";
}

function appHideLoading(){
    document.getElementById('divAppLoading').style.visibility = "hidden";
}

function appElementDocOffset(elem){
	var curleft = curtop = 0;
	if (elem.offsetParent) {
		do {
			curleft += elem.offsetLeft;
			curtop += elem.offsetTop;
		} while (elem = elem.offsetParent);
	}
	return [curleft, curtop];
}

function appStringifyKey(objKey){
    var strKey = objKey + ''; //key is always string
    strKey = JSON.stringify(strKey); //jsonify stored key to match json
    strKey = strKey.substring(1,strKey.length-1); //strip quotes from jsonified key
    return strKey;
}

function appCallOnLoad(){
    //init params
    appParams = getQueryVars();
    //call user defined appOnLoad
    try{
        appOnLoad();
    }
    catch (e){}
}

function getQueryVars()
{
    var ret, pairs, i, params;
    ret = {};
    pairs = location.search.substr(1).split('&');
    for (i = 0; i < pairs.length; ++i) {
        params = pairs[i].split('=');
        if (params.length == 2) {
            ret[params[0]] = unescape(params[1]);
        }
    }
    return ret;
}

function appAjaxCall(url, asyncCallback){
	var async = (asyncCallback) ? true : false;
	var xmlhttp = appGetXmlHttp();
	xmlhttp.onreadystatechange = function() {
		if((async)&&(xmlhttp.readyState==4)) {
                        appHideLoading();
			eval(asyncCallback + '(' + appParseResponse(xmlhttp.responseText) + ')');
		}
	};
        appShowLoading();
	xmlhttp.open("GET", url, async);
	xmlhttp.send(null);
	if (!async){
            appHideLoading();
            return eval('(' + appParseResponse(xmlhttp.responseText) + ')');
	}
}

function appParseResponse(str){
    str = str.replace(/^\s+|\s+$/g, ''); //trim spaces from response
    if (str=='') str = 'null';
    return str;
}

function appGetXmlHttp(){
	var xmlHttp;
	try {  // Firefox, Opera 8.0+, Safari  
		xmlHttp=new XMLHttpRequest();  
	}
	catch(e) {  // Internet Explorer  
		try {    
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    
		}
		catch (e) {    
			try {      
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");      
			}
			catch (e) {      
				alert("Your browser does not support AJAX!");      
				return false;      
			}    
		}  
	}
	return xmlHttp;
}

