﻿/// <reference path="../jquery-1.3.2.min-vsdoc.js" />



function getQueryStringValueFromUrl(key, url) {
    var QueryString = url.substr(url.indexOf('?') + 1);
    var keyValueArray = QueryString.split('&');
    for (var i in keyValueArray) {
        var tmpPair = keyValueArray[i].split('=');
        if (tmpPair[0] == key) return tmpPair[1];
    }
    return '';
}



function clearSelection()
{
    var sel;
    if (document.selection && document.selection.empty)
    {
        try
        {
            document.selection.empty();
        }
        catch (err) { }
    }
    else if (window.getSelection)
    {
        sel = window.getSelection();
        if (sel && sel.removeAllRanges)
        {
            sel.removeAllRanges();
        }
    }
}



function getElementsByClassName(classname, node) {
    if (!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for (var i = 0, j = els.length; i < j; i++)
        if (re.test(els[i].className)) a.push(els[i]);
    return a;
}

function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") //IE route
    {
        target.onselectstart = function() { return false; }
    }
    else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
    {
        target.style.MozUserSelect = "none";
    }
    else //All other route (ie: Opera)
    { }
    //target.style.cursor = "default";
}



function serialize(_obj) {
    // Let Gecko browsers do this the easy way
    if (_obj == null) return '';
    if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined') {
        return _obj.toSource();
    }

    // Other browsers must do it the hard way
    switch (typeof _obj) {
        // numbers, booleans, and functions are trivial:  
        // just return the object itself since its default .toString()  
        // gives us exactly what we want  
        case 'number':
        case 'boolean':
        case 'function':
            return _obj;
            break;

        // for JSON format, strings need to be wrapped in quotes  
        case 'string':
            return '\'' + _obj + '\'';
            break;

        case 'object':
            var str;
            if (_obj.constructor === Array || typeof _obj.callee !== 'undefined') {
                str = '[';
                var i, len = _obj.length;
                for (i = 0; i < len - 1; i++) { str += serialize(_obj[i]) + ','; }
                str += serialize(_obj[i]) + ']';
            }
            else {
                str = '{';
                var key;
                for (key in _obj) { str += key + ':' + serialize(_obj[key]) + ','; }
                str = str.replace(/\,$/, '') + '}';
            }
            return str;
            break;

        default:
            return 'UNKNOWN';
            break;
    }
}




Settings = {

    Values: [],

    Save: function(key, value, callback) {
        // Debug
        Debug.Add('numberofsavesettings', 'Save-settings count', Debug.GetValue('numberofsavesettings') + 1);
        // Debug

        xhr = $.ajax({
            type: "POST",
            url: '/Setting?key=' + key,
            data: "value=" + value,
            dataType: "html",
            success: function(json) {
                var jsonObject = eval('(' + json + ')');
                if (jsonObject.result != "ok") alert('Ajax result from Setting.Save: ' + jsonObject.result);

                Settings.Remove(key);
                Settings.Values.push({ 'key': key, 'value': value });

                if (callback != null) callback();
            },
            error: function(xhr, ajaxOptions, thrownError) {
                if (thrownError + '' == "undefined") {
                    return false;
                }
                if (xhr.statusText == "Bad Request") {
                    $(target).html(xhr.responseText);
                    return false;
                }
                if (xhr.statusText == "Internal Server Error") {
                    $(target).html(xhr.responseText);
                    return false;
                }
                if (xhr.statusText == "" && thrownError == "undefined") return false;
                alert('[letsmixload] [target_url:' + target_url + '] xhr: ' + serialize(xhr));
                alert('[letsmixload] xhr.statusText: ' + xhr.statusText);
                alert('[letsmixload] thrownError: ' + thrownError);
                return false;
            }
        });

        /*
        $.post('/Setting?key=' + key, { 'value': value }, function(json) {
            var jsonObject = eval('(' + json + ')');
            if (jsonObject.result != "ok") alert('Ajax result from Setting.Save: ' + jsonObject.result);

            Settings.Remove(key);
            Settings.Values.push({ 'key': key, 'value': value });

            if (callback != null) callback();
        });
        */
    },


    Get: function(key, getcallback) {
        var theKey = key;

        /* Debug */
        Debug.Add('numberofgetsettings', 'Get-settings count', Debug.GetValue('numberofgetsettings') + 1);
        Debug.Add('numberofgetsettings_array_length', 'Settings array length', Settings.Values.length);
        Debug.Add('numberofgetsettings_array_size', 'Settings array size', serialize(Settings.Values).length);
        Debug.Add('numberofgetsettings_array', 'Settings array', serialize(Settings.Values));
        /* Debug */

        var callback;
        if (getcallback != null) {
            callback = getcallback;
        }

        var url = '/Setting?key=' + theKey + '&rand=' + randomString(10);

        /* Debug */
        Debug.Add('settings_get_url', 'Settings get url', url);
        /* Debug */

        $.getJSON(url, function(json) {

            if (theKey == Playlist.SettingsKey) {
                /* Debug */
                Debug.Add('settings_playque', 'settings_playque', json);
                /* Debug */
            }

            /*
            json = json.replace("\"[", "[");
            json = json.replace("]\"", "]");

            try {
            var jsonObject = eval('(' + json + ')');
            }
            catch (err) {
            alert('Unable to parse json: ' + json);
            }

            jsonObject.value = jsonObject.value.substr(1, jsonObject.value.length - 3);
            */

            try {
                console.log('Got setting for ' + theKey + ' from server: ' + json.server + ' Value: ' + json.value);
            }
            catch (err) {
                //alert('Unable to log');
            }

            if (callback != null) callback(json.value);
        });
    },

    Remove: function(key) {
        for (var i in Settings.Values) {
            if (Settings.Values[i].key == key) {
                Settings.Values.splice(i, 1);
            }
        }
    },

    GetValue: function(key) {
        for (var i in Settings.Values) {
            if (Settings.Values[i].key == key) return Settings.Values[i].value;
        }
        return null;
    }


};





Debug = {

    Disable: true,

    Values: [],

    Add: function(key, publicName, val) {
        if (!this.Disable) {
            if ($('#debug-info').size() == 0) $('body').prepend('<div id="debug-info" style="font-size:9px; position:fixed; top:10px; left:200px; "></div>');

            if ($('#' + key).size() == 0) $('#debug-info').prepend('<div id="' + key + '">' + publicName + ':<span style="color:#fcc;"></span></div>');
            $('#' + key + ' span').html(val);

            this.Remove(key);
            this.Values.push({ 'key': key, 'value': val });
        }
    },

    Remove: function(key) {
        for (var i in this.Values) {
            if (this.Values[i].key == key) {
                this.Values.splice(i, 1);
            }
        }
    },

    GetValue: function(key) {
        for (var i in this.Values) {
            if (this.Values[i].key == key) return this.Values[i].value;
        }
        return null;
    }
};






function randomString(length) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = length;
    var randomstring = '';
    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }
    return randomstring;
}




function evalOnEnter(myfield, e, func) {
    var keycode;
    if (window.event) {
        keycode = window.event.keyCode;
    }
    else if (e) {
        keycode = e.which;
    }
    else {
        return true;
    }

    if (keycode == 13) {
        eval(func);
        return false;
    }
    else {
        return true;
    }
}



// Removes leading whitespaces
function LTrim(value) {

    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim(value) {

    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");

}

// Removes leading and ending whitespaces
function trim(value) {

    return LTrim(RTrim(value));

}




function generateRandomColorHex() {
    colors = new Array(14);
    colors[0] = "0"; colors[1] = "1"; colors[2] = "2"; colors[3] = "3"; colors[4] = "4"; colors[5] = "5"; colors[5] = "6"; colors[6] = "7"; colors[7] = "8"; colors[8] = "9"; colors[9] = "a"; colors[10] = "b"; colors[11] = "c"; colors[12] = "d"; colors[13] = "e"; colors[14] = "f";

    digit = new Array(5);
    color = "";
    for (i = 0; i < 6; i++) {
        digit[i] = colors[Math.round(Math.random() * 14)];
        color = color + digit[i];
    }
    return "#" + color;
}


var xhr;


function letsmixload(target, target_url, callback) {
    $(target).append('<span class="ajax-loader"></span>');

    // Add something random to the url to avoid cached data (primarily for IE, where this seems to be an issue)
    if (target_url.indexOf('?') > 0) {
        target_url = target_url + '&' + randomString(6);
    }
    else {
        target_url = target_url + '?' + randomString(6);
    }

    // Don't want to abort module loading since that makes it impossible to load them in parallell
    //if (xhr !== undefined) { xhr.abort(); }

    xhr = $.ajax({
        type: "GET",
        url: target_url,
        dataType: "html",
        success: function(data) {
            $(target).html(data);
            if (callback != null) callback();
        },
        error: function(xhr, ajaxOptions, thrownError) {
            if (thrownError+'' == "undefined") {
                return false;
            }
            if (xhr.statusText == "Bad Request") {
                $(target).html(xhr.responseText);
                return false;
            }
            if (xhr.statusText == "Internal Server Error") {
                $(target).html(xhr.responseText);
                return false;
            }
            if (xhr.statusText == "" && thrownError == "undefined") return false;
            alert('[letsmixload] [target_url:' + target_url + '] xhr: ' + serialize(xhr));
            alert('[letsmixload] xhr.statusText: ' + xhr.statusText);
            alert('[letsmixload] thrownError: ' + thrownError);
            return false;
        }
    });
    return false;
}



jQuery.fn.outerHTML = function() {
    return $('<div>').append(this.eq(0).clone()).html();
};



function findSWF(movieName) {
    return document.getElementById(movieName);
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}


var current_favicon = 'favicon.gif';

function setFavicon(iconname) {
    var current_href = current_favicon;
    var new_href = iconname;

    if (current_href != new_href) {
        var link = document.createElement('link');
        link.type = 'image/x-icon';
        link.rel = 'shortcut icon';
        link.href = '/content/img/icons/' + iconname;
        document.getElementsByTagName('head')[0].appendChild(link);
        $('head link[rel="shortcut icon"]').remove();
        current_favicon = iconname;
    }
};




ModalBox = {
    LoadContent: function(url, callback) {
        if ($('#modal-box').size() == 0) {
            $('body').prepend('<div id="modal-box"><div class="blackout"></div><div class="wrapper"><div class="content"></div></div></div>');
        }
        var box = $('#modal-box');
        var background = $('#modal-box .blackout');
        var content = $('#modal-box .content');
        var wrapper = $('#modal-box .wrapper');


        // Dismiss modal box if user clicks outside the box
        $(background).click(function() {
            ModalBox.Close();
        });

        $(content).html('<span class="ajax-loader"></span>');
        $(box).show();
        // TODO: position box
        $(wrapper).css('left', parseInt(($(window).width() - $(wrapper).width()) / 2, 10));

        $(content).load(url, function(/*responseText, textStatus, xhr*/) {
            /* Error handling */
            /*
            if (xhr.statusText == "Bad Request" || xhr.statusText == "Internal Server Error") {
            $(this).html(xhr.responseText);
            return false;
            }
            */

            if (callback != null) callback();
        });
    },

    Close: function() {
        var box = $('#modal-box');
        var content = $('#modal-box .content');
        $(content).html('');
        $(box).hide();
    }

};




function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}


String.prototype.capitalize = function() { //v1.0
    return this.replace(/\w+/g, function(a) {
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};
