function page_to_src(v)
{
    return "/digitalsignage/"+v;
}

function $() {
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        if (arguments.length == 1)
            return element;
        elements.push(element);
    }
    return elements;
}

function is_enterpress_event(e)
{
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;

    if (keycode == 13)
        return true;
    return false;
}

function xtractFile(data){
    var m = data.match(/(.*)\/([^\/\\]+\.\w+)$/);
    return {path: m[1], file: m[2]}
}

function makeDotDotDot(str,size){
    if (str.length>size)
        return str.substring(0,size-2)+'...';
    return str;
}

function isInt (str)
{
    var i = parseInt (str);
    if (isNaN (i))
        return false;
    if (i.toString() != str)
        return false;
    return true;
}

function fixevent(e) {
     return (!e) ? window.event : e;
}

function findtarget(e) {
     if (e.target) targ = e.target;
     else if (e.srcElement) targ = e.srcElement;
  if (targ.nodeType == 3) // defeat Safari bug
     targ = targ.parentNode;
     return targ;
}

function seconds_to_mmss(secs)
{
    var seconds = secs%60;
    if (seconds <10)
        seconds = '0'+seconds;
    return parseInt(secs/60)+":"+seconds;
}

function str_replace(bad_str,good_str,big_str)
{
    var newstr='';
    var splitup = big_str.split(bad_str);
    for(var i=0; i<splitup.length-1; i++)
        newstr+=splitup[i]+good_str;
    newstr+=splitup[splitup.length-1];
    return newstr;
}

function escape_for_html(s)
{
    var n= str_replace("'" , "&#039;", s);
    return str_replace('"' , "&#034;", n);
}

function getCookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ';', len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires ) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name+'='+escape( value ) +
        ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
        ( ( path ) ? ';path=' + path : '' ) +
        ( ( domain ) ? ';domain=' + domain : '' ) +
        ( ( secure ) ? ';secure' : '' );
}

function show_element(el){
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        element.style.display='block';
    }
}

function hide_element(el){
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        element.style.display='none';
    }
}

function toggle(obj) {
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element == 'string')
            element = document.getElementById(element);
        element.style.display= (( element.style.display != 'none' )? 'none' : 'block' );
    }
}

function count_children(myElement)
{
   if (!myElement)
       return 0;
   var count=0;
   var child = myElement.firstChild;
   while (child!=null)
   {
       count++;
       child = child.nextSibling;
   }
   return count;
}

function removeChildren(list)
{
    if (list==null) return;
    var child = list.firstChild;
    while(child!=null)
    {
        list.removeChild(child);
        child = list.firstChild;
    }
}

function removeElementbyName(element_name)
{
    d = document.getElementById(element_name);
    p = d.parentNode ? d.parentNode : d.parentElement;
    p.removeChild( d );
}

//this function is case insensitive
String.prototype.beginsWith = function(t) {
    return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
}
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}
function alert_obj(obj)
{
    var str2='';
    for(s in obj)
        str2+=  "obj["+s+"]"+obj[s]+"\n";
    alert(str2);
}

function xml_text_node(elem,nam)
{
    try{
        return elem.getElementsByTagName(nam)[0].firstChild.nodeValue;
    }
    catch(e){
        return "";
    }
}

//------------------------------------------------------
//source: Zedwood
//license: CC-GNU LGPL
//usage:  ZDImg.arr.push("images/spacer.gif");
//        ZDImg.preloadImages();
var ZDImg = {
    arr : [
        "images/btn_rightcap_hover.png",
        "images/btn_rightcap.png",
        "images/btn_leftcap_hover.png",
        "images/btn_leftcap.png",
        "images/btn_bg.png",
        "images/btn_bg_hover.png",
        ],

    img : null,
    preloadImages : function()
    {
        if (document.images)
        {
            ZDImg.img = new Array();
            for(i=0;i<ZDImg.arr.length;i++)
            {
                ZDImg.img[i] = new Image();
                ZDImg.img[i].src = page_to_src(ZDImg.arr[i]);
            }
        }
    }
}
ZDImg.preloadImages();

//------------------------------------------------------
//source: Zedwood
//license: CC-GNU LGPL
//usage:
//     var e = DOMelement('div');
//     e.setAttribute('id'   ,'my_div_id123');
//     e.setAttribute('style','border:1px solid #000000;');
//     var element = e.createElement();
//     document.body.appendChild( element );
function DOMelement(txt)
{
    var o = new Object();
    o.elementname   = txt;
    o.attributes    = new Object();
    o.innerHTML     = '';
    o.innerText     = '';
    o.setAttribute = function(attribute,attribute_value)
    {
        o.attributes[attribute] = attribute_value;
    }
    o.createElement = function()
    {
        var attribute_str = '';
        var css_style_str = '';
        for(attribute_name in o.attributes)
        {
            if (attribute_name.toLowerCase() != 'style')
                attribute_str+= attribute_name+"='"+escape(o.attributes[attribute_name])+"'";
            else
                css_style_str= o.attributes[attribute_name];
        }

        var element;
        try
        {
            element = document.createElement("<"+o.elementname+" "+attribute_str);//IE
        }
        catch (e)
        {
            element = document.createElement( o.elementname );
            for(attribute_name in o.attributes)
                element.setAttribute( attribute_name , o.attributes[attribute_name] );
        }
        if (css_style_str.length>0)
            element.style.cssText=css_style_str;
        if (o.innerHTML && o.innerHTML.length>0)
            element.innerHTML = o.innerHTML;
        else if (o.innerText && o.innerText.length>0)
            element.appendChild( document.createTextNode(o.innerText) );
        return element;
    }

    return o;
}
//------------------------------------------------------
//source: Zedwood Inc, Quirksmode(createXMLHTTPObject)
//license: CC-GNU LGPL
//usage: AJAX.execute(functionMakeQueryString,functionCallBack,paramsObj);
//function doSomething()
//{
//    var paramsobj = new Object();
//    paramsobj.genre_id = '1234';

//    AJAX.execute(buildQueryString, functionCallBack, paramsobj);
//}
//function functionMakeQueryString(paramsobj)
//{
//    var myObject = new Object();
//    myObject.action     = 'set_genre';
//    myObject.id         = g_raceid++;
//    myObject.session    = g_session;
//    return myObject;
//}
//
//function functionCallBack(ajaxobj,paramsobj)
//{
//    alert(ajaxobj.responseText);
//    alert(ajaxobj.responseXML);
//}
var AJAX = {
    XMLHttpFactories : [
        function () {return new XMLHttpRequest()},
        function () {return new ActiveXObject("Msxml2.XMLHTTP")},
        function () {return new ActiveXObject("Msxml3.XMLHTTP")},
        function () {return new ActiveXObject("Microsoft.XMLHTTP")}
    ],
    createXMLHTTPObject : function ()
    {
        xmlhttp = null;
        for (var i=0;i<AJAX.XMLHttpFactories.length;i++) {
            try {
                xmlhttp = AJAX.XMLHttpFactories[i]();
            }
            catch (e) {
                continue;
            }
            break;
        }
        return xmlhttp;
    },
    objectToURL : function (url,query_str_obj)
    {
           url_str=url + '?';
           for(property in query_str_obj)
               url_str+= property + "=" + escape( query_str_obj[property] ) + "&";
           return url_str;
    },
    execute : function (functionMakeQueryString, functionCallBack, paramsobj)
    {
        request = new Object();
        request.ajaxRequest = AJAX.createXMLHTTPObject();
        request.sendRequest = function()
        {
            if(request.ajaxRequest.readyState == 1)
            {   //never happen, cause we create a new request each time
                alert('error: still processing previous request');
                return;
            }

            queryobj= functionMakeQueryString(paramsobj);
            baseurl = page_to_src('php_ajax.php');
            fullurl = AJAX.objectToURL(baseurl, queryobj);
            request.ajaxRequest.open('get', fullurl);
            request.ajaxRequest.onreadystatechange = function()
            {
                if(request.ajaxRequest.readyState == 4 && request.ajaxRequest.status == 200)
                {
                    //alert(request.ajaxobj.responseText);
                    functionCallBack(request.ajaxRequest,paramsobj);
                }
            }
            request.ajaxRequest.send(null);
        }
        request.sendRequest();
        return request;
    }
};
//------------------------------------------------------
//source: http://www.dustindiaz.com/rock-solid-addevent/ cc-gnu LGPL
//license: CC-GNU LGPL
//usage: addEvent(window,'resize', functionName);
function addEvent( obj, type, fn ) {
    if (obj.addEventListener) {
        obj.addEventListener( type, fn, false );
        EventCache.add(obj, type, fn);
    }
    else if (obj.attachEvent) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
        EventCache.add(obj, type, fn);
    }
    else {
        obj["on"+type] = obj["e"+type+fn];
    }
}

var EventCache = function(){
    var listEvents = [];
    return {
        listEvents : listEvents,
        add : function(node, sEventName, fHandler){
            listEvents.push(arguments);
        },
        flush : function(){
            var i, item;
            for(i = listEvents.length - 1; i >= 0; i = i - 1){
                item = listEvents[i];
                if(item[0].removeEventListener){
                    item[0].removeEventListener(item[1], item[2], item[3]);
                };
                if(item[1].substring(0, 2) != "on"){
                    item[1] = "on" + item[1];
                };
                if(item[0].detachEvent){
                    item[0].detachEvent(item[1], item[2]);
                };
                item[0][item[1]] = null;
            };
        }
    };
}();
//---------------------------
//source: Yoogli Inc and http://www.quirksmode.org/viewport/compatibility.html
//license: CC-LGPL
//usage: a = YGWin.getWindowDimensions();
//       b = YGWin.getDocumentDimensions();
//       c = YGWin.getCenteredWindowCoords();
var YGWin = {
    docDimensions : null,
    winDimensions : null,

    //get is public
    getWindowDimensions : function()
    {
        if (!YGWin.winDimensions) YGWin.winDimensions = YGWin.findWindowDimensions();
        return YGWin.winDimensions;
    },

    //find is public
    findWindowDimensions : function()
    {
        var x,y;
        if (self.innerHeight) // all except Explorer
        {
            x = self.innerWidth;
            y = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight)
            // Explorer 6 Strict Mode
        {
            x = document.documentElement.clientWidth;
            y = document.documentElement.clientHeight;
        }
        else if (document.body) // other Explorers
        {
            x = document.body.clientWidth;
            y = document.body.clientHeight;
        }
        return {"width":x, "height":y};
    },

    //get is public
    getDocumentDimensions : function ()
    {
        if (!YGWin.docDimensions) YGWin.docDimensions = YGWin.findDocumentDimensions();
        return YGWin.docDimensions;
    },
    //find is private
    findDocumentDimensions : function ()
    {
        var x,y;
        var test1 = document.body.scrollHeight;
        var test2 = document.body.offsetHeight
        if (test1 > test2) // all but Explorer Mac
        {
            x = document.body.scrollWidth;
            y = document.body.scrollHeight;
        }
        else
        {
            // Explorer Mac; would also work in:
            // Explorer 6 Strict, Mozilla and Safari
            x = document.body.offsetWidth;
            y = document.body.offsetHeight;
        }
        return {"width":x, "height":y};
    },
    windowResize : function()
    {
        YGWin.docDimensions = YGWin.findDocumentDimensions();
        YGWin.winDimensions = YGWin.findWindowDimensions();
    },
    getCenteredWindowCoords : function(windowWidth,windowHeight)
    {
        dim = YGWin.getWindowDimensions();
        verticalScroll   = 0;
        horizontalScroll = 0;
        vPos = Math.round(verticalScroll+((dim.height-windowHeight)/2));
        hPos = Math.round(horizontalScroll+((dim.width-windowWidth)/2));
        top_coord  = (vPos < 0)?0:vPos;
        left_coord = (hPos < 0)?0:hPos;
        return {"top":top_coord, "left":left_coord};
    }
};
//---------------------------

addEvent(window,'resize',YGWin.windowResize);
addEvent(window,'unload',EventCache.flush);
