function $(id) { return document.getElementById(id) }

//----- date time functions -------------------------------------------------------------

//
// local time dictated by time zone and server time (don't trust client time)
//
function VIET_vnl_ServerTime() {
    this.inited = false;
    this.iClientTimeDiff = 0; // time disparency between client and server
    this.iServerTimeDiff = 0;
}
VIET_vnl_ServerTime.prototype = {
    //
    // call this function when page init
    //
    init: function() {
        var me = this;
        YAHOO.util.Connect.asyncRequest('GET', '/json/getServerTime.php', 
            {success:function(obj) {
                    try {
                        var dtLocal = new Date();

                        var ar = eval("(" + obj.responseText + ")");
                        var dtClientTimeByServer = new Date();  // client time dictated by server
                        dtClientTimeByServer.setTime(Date.parse(ar.clientTime));
                        me.iClientTimeDiff = dtClientTimeByServer.valueOf() - dtLocal.valueOf();

                        var dtServerTime = new Date();
                        dtServerTime.setTime(Date.parse(ar.serverTime));
                        me.iServerTimeDiff = dtServerTime.valueOf() - dtLocal.valueOf();
                        
                        me.inited = true;
                    }
                    catch(ex) {}
                }
            });
    },
    
    //
    // get local time dictated by server (don't trust client machine)
    //
    getClientTime: function() {
        if( !this.inited )
            this.init();

        // if this ServerTime object is not yet initiated, time return might not be correct this time
        var dtLocal = new Date();
        dtLocal.setTime( dtLocal.valueOf() + this.iClientTimeDiff );
        return dtLocal;
    },
    
    getServerTime: function() {
        if( !this.inited )
            this.init();

        var dtLocal = new Date();
        dtLocal.setTime( dtLocal.valueOf() + this.iServerTimeDiff );
        return dtLocal;
    }
}
var oServerTime = new VIET_vnl_ServerTime();
// for backward compatibility
function getLocalTime() { return oServerTime.getClientTime(); }
function getServerTime() { return oServerTime.getServerTime(); }


function VIET_vnl_util_ParseDateTimeFromMySQL(s) {
    var ar = s.split(' '), sd = ar[0], st = ar[1];
    var arD = sd.split('-'), arT = st.split(':');
    var dt = new Date(arD[0], parseInt(arD[1], 10)-1, arD[2], arT[0], arT[1], arT[2], 0);
    /*dt.setDate(1); // need this to prevent month moving when today is 31
    dt.setFullYear(arD[0]); dt.setMonth(parseInt(arD[1], 10)-1); dt.setDate(arD[2]);
    dt.setHours(arT[0]); dt.setMinutes(arT[1]); dt.setSeconds(arT[2]);*/
    return dt;
}
function VIET_vnl_util_ToMySQLTime(dt) {
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    var h = dt.getHours();
    var min = dt.getMinutes();
    var s = dt.getSeconds();
    return dt.getFullYear() + '-' + (m<10 ? '0' : '') + m + '-' + (d<10 ? '0' : '') + d
        + ' ' + (h<10 ? '0' : '') + h + ':' + (min<10 ? '0' : '') + min + ':' + (s<10 ? '0' : '') + s;
}
function VIET_vnl_util_ToMySQLDate(dt) {
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    var h = dt.getHours();
    return dt.getFullYear() + '-' + (m<10 ? '0' : '') + m + '-' + (d<10 ? '0' : '') + d;
}
function VIET_vnl_util_ToTvGuideTime(dt) {
    return (dt.getHours()>12 ? (dt.getHours()-12) : dt.getHours()) + ':' + (dt.getMinutes()<10 ? '0' : '') + dt.getMinutes();
}
function VIET_vnl_util_ToTvGuideTimeAmPm(dt) {
    return (dt.getHours()<12 ? 'AM' : 'PM');
}

//
// Display month in this format: September 2007.
// sLang: language - optional (default = English) - 'en' for English, 'vn' for Vietnamese
// sVer: version (short or long) - optional (default = long) - 's' for short, 'l' for long
//
function VIET_vnl_util_ToMonthString(dt, sLang, sVer) {

    // language
    if( sLang==null ) sLang='en';
    var arM = VIET_vnl_util_MonthNames[sLang];
    if( arM==null )
        arM = VIET_vnl_util_MonthNames['en'];

    // version
    if( sVer==null ) sVer = 'l';
    var arM2 = arM[sVer];
    if( arM2==null )
        arM2 = arM['l'];

    return (sLang=='vn' ? 'Thang ' : '') + arM2[dt.getMonth()] + (sLang=='vn' ? ', ' : ' ') + dt.getFullYear();
}

//
// Display date in this format: Friday, November 2, 2007
// sLang: language - optional (default = English) - 'en' for English, 'vn' for Vietnamese
// sVer: version (short or long) - optional (default = long) - 's' for short, 'l' for long
//
function VIET_vnl_util_ToDateString(dt, sLang, sVer) {

    // language
    if( sLang==null ) sLang='en';
    var arD = VIET_vnl_util_DateNames[sLang];
    if( arD==null )
        arD = VIET_vnl_util_DateNames['en'];

    var arM = VIET_vnl_util_MonthNames[sLang];
    if( arM==null )
        arM = VIET_vnl_util_MonthNames['en'];
    
    // version
    if( sVer==null ) sVer = 'l';
    var arD2 = arD[sVer];
    if( arD2==null ) 
        arD2 = arD['l'];
    var arM2 = arM[sVer];
    if( arM2==null )
        arM2 = arM['l'];

    if( sLang=='vn' ) {
        return arD2[dt.getDay()] + ', ' + dt.getDate() + ' thang ' + arM2[dt.getMonth()] + (sVer!='xs' ? ', ' + dt.getFullYear() : '');
    }
    else if( sLang=='en' ) {
        if( sVer=='xs' )
            return arD2[dt.getDay()] + ' ' + arM2[dt.getMonth()] + '/' + dt.getDate();
        else
            return arD2[dt.getDay()] + ', ' + arM2[dt.getMonth()] + ' ' + dt.getDate() + ', ' + dt.getFullYear();
    }
}

var VIET_vnl_util_MonthNames = {
    en: {
            l: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
            s: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            xs: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
        },
    vn: {
            l: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
        }
};
var VIET_vnl_util_DateNames = {
    en: {
            l: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            s: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
            xs: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
    },
    vn: {
            l: ['Chủ Nhật', 'Thứ Hai', 'Thứ Ba', 'Thứ Tư', 'Thứ Năm', 'Thứ Sáu', 'Thứ Bảy']
    }
}

//
// other
//
function VIET_vnl_util_GetChannelName(iChannelId) {
    return (iChannelId==1 ? 'HTV7' : 'HTV9');
}

//
// DECE: Delay Execution on Continuous Events
//
function DECE( piDelay )
{
    var thExec        = null;
    this.Exec            = function( pFunction, paArgs )
    {
        if( thExec!=null )
        {
            if( thExec.bRunning==null || thExec.bRunning==false )
            {
                // last call is not yet started -> cancel it
                clearTimeout(thExec);
            }
            else
            {
                // last call is running -> let it run and schedule another thread
            }
        }

        //
        // if already started and running, there is nothing we can do;
        // just execute another instance
        //

        thExec    = setTimeout(
            function()
            {
                thExec.bRunning = true;
                if( paArgs==null )
                    pFunction()
                else
                    pFunction(paArgs);
                thExec.bRunning = false;
            },
            piDelay );
    }
}

//
// This utility function resolves the string movieName to a Flash object reference based on browser type.
//
function getMovieName(movieName){
      if (navigator.appName.indexOf("Microsoft") != -1) {
      return window[movieName]
    }else {
      return document[movieName]
    }
}

function trim(s) {
    return s.replace(/^[\s]*/, '').replace(/[\s]*$/, '');
}

//
// cookies
//
function getCookie(name) {
    var pairs = document.cookie.split(";");
    for( var i=0; i<pairs.length; i++ ) {
        var arP = pairs[i].split("=");
        arP[0] = trim(arP[0]);
        if( arP[0]==name )
            return unescape(arP[1]).replace('+', ' ');
    }
    return null;
}
//
// return array of all cookies
//
function getCookies() {
    var ar = [];
    var pairs = document.cookie.split(";");
    for( var i=0; i<pairs.length; i++ ) {
        var arP = pairs[i].split("=");
        arP[0] = trim(arP[0]);
        ar[ arP[0] ] = unescape(arP[1]).replace('+', ' ');
    }
    return ar;
}
function $_COOKIES(name) {
    return getCookie(name);
}
function setCookie(cookieName, cookieValue, nDays) {
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0)
        nDays=1;
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
}

//
// this function get url parameters
//
function $_GET( name ) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

/*
 * Periodically trigger a call.
 * iSeconds: interval in seconds (seconds between triggers)
 */
function VIET_vnl_util_Timer(iSeconds) {
    this.thTimer = null;
    this.iInterval = iSeconds==null ? 1 : iSeconds;
    this.arEvents = []
}
VIET_vnl_util_Timer.prototype = {
    Start: function() {
        this.run();
    },

    Stop: function() {
        if( this.thTimer!=null )
            clearTimeout(this.thTimer);
    },

    run: function() {
        for( var i=0, len=this.arEvents.length; i<len; i++ )
            this.arEvents[i].handler(this.arEvents[i].arguments);
        var me = this;
        this.thTimer = setTimeout(function() { me.run() }, this.iInterval*1000);
    },

    //
    // functions that will be called in each interval
    //
    RegisterEvent: function(fnHandler, oArgs) {
        this.arEvents.push( {handler:fnHandler, arguments:oArgs} );
    }
}

//---- JSON or XML URLs -------------------------------------------------------------------------
function getJsonUrl(arData) {
    var action = arData['action'];
    var channel = arData['channel'];
    if( channel==null )
        channel = 1;
    channel += '-' + VIET_vnl_util_GetChannelName(channel);

    if( action=='playlist' ) {
        if( arData['type']=='ondemand' ) {
            // play a tv program - must supply guideId - group to keep cache-dir from having too many files
            return '/playlist/ondemand' + '/' + Math.round(arData['guideId']/1000) + (arData['preview']=='no' ? '/preview/no' : '') 
                + (arData['preview']=='no' ? '' : '/lang/' + oGlobal.sCurrLang + '/seed/' + Math.floor(Math.random()*1000))
                + '/guide/' + arData['guideId'] 
                + (arData['format']=='json' ? '.json' : '');
        }
        else if( arData['type']=='live' ) {

            // play live tv 

            var dtLocal = oServerTime.getServerTime();
            var h = dtLocal.getHours();
            var min = dtLocal.getMinutes();
            var sLocalDate = VIET_vnl_util_ToMySQLDate(dtLocal);
            var sLocalTime = sLocalDate + ' ' + (h<10 ? '0' : '') + h + ':' + (min<10 ? '0' : '') + min + ':00'; // so air-time is rounded to minutes (cache efficiency)
            sLocalTime = sLocalTime.replace(/:/g, '_');

            return '/playlist/live' + '/' + sLocalTime + '/channel/' + channel + (arData['format']=='json' ? '.json' : '');
            
        }
    }
    else if( action=='program-item' ) {
        //
        // get info about a tv guide item
        //
        if( arData['type']=='info' ) {
            return '/program-item/group/' + Math.round(arData['guideId']/1000) + '/id/' + arData['guideId'] 
                + (arData['format']=='json' ? '.json' : '');
        }
        else if( arData['type']=='thumbnail' ) {
            return '/program-item/group/' + VIET_vnl_util_ToMySQLDate(arData['airTime'])
                + '/get/thumbnail/docId/' + arData['thumbDocId'] + (arData['format']=='json' ? '.json' : '');
        }
    }
    else if( action=='genre' ) {
        return '/genre/id/' + (arData['genreId']==null || arData['genreId']=='' ? 'toprated' : escape(arData['genreId'])) 
            + (arData['format']=='json' ? '.json' : '');
    }
    else if( action=='program' ) {
        return '/program/date/' + escape((arData['date']==null ? VIET_vnl_util_ToMySQLDate(getLocalTime()) : arData['date'])) 
            + '/channel/' + channel + (arData['format']=='json' ? '.json' : '');
    }
    else if( action=='tag' ) {
        return '/tag/group/' + Math.round(arData['guideId']/1000) + '/guide/' + arData['guideId'] + (arData['format']=='json' ? '.json' : '');
    }
    else if( action=='search' ) {
        return '/zf/search/index/keyword/' + escape(arData['keyword'].replace(/ /g, '-').toLowerCase()) + (arData['page']>1 ? '/page/' + arData['page'] : '')
    }

    return '';
}

function validEmail(email) {
    return email.match(/^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i)!=null;
}
