﻿// <reference name="MicrosoftAjax.js" />
/// <reference name="~/JS/Pager.js" />

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+$/, "");
}

String.prototype.replaceAll = function(strA, strB) {
    return this.replace(new RegExp(strA, "g"), strB);
}

function SaveAsConnect() {
    www.playinstar.com.Services._2009._05.LocalServices.SaveAsConnect()
}

function doClick(buttonName, e) {
    //the purpose of this function is to allow the enter key to 
    //point to the correct button to click.
    var key;

    if (window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox

    if (key == 13) {
        //Get the button the user wants to have clicked
        var btn = document.getElementById(buttonName);
        if (btn != null) { //If we find the button click it
            btn.click();
            event.keyCode = 0
        }
    }
}

function doFunction(functionName, e) {
    //the purpose of this function is to allow the enter key to 
    //point to the correct button to click.
    var key;

    if (window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox

    if (key == 13) {
        eval(functionName);
    }
}

function doCallback(callback, e) {
    //the purpose of this function is to allow the enter key to 
    //point to the correct button to click.
    var key;
    
    if (window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.keyCode || e.which;     //firefox

    if (key == 13) {
        callback();
        e.cancelBubble = true;
    }

    return key != 13;
}

// In JavaScript, dividing integer values yields a floating point result (unlike in Java, C++, C)
// To find the integer quotient, reduce the numerator by the remainder first, then divide.
function divide(numerator, denominator) {
    var remainder = numerator % denominator;
    var quotient = (numerator - remainder) / denominator;
    
    return quotient;
}

// The function trims and leading or trailing spaces from a string.
function trim(str) {
    if ((!str && str != '') || typeof str != 'string')
        return null;
    else
        return str.replace(/^\s+|\s+$/g, '');
}

function leapyear(a) {
    return (((a % 4 == 0) && (a % 100 != 0)) || (a % 400 == 0));
}

function getAge(day, month, year) {
    var result = 0;

    if ((month < 1) || (month > 12) || (day < 1) || (day > 31) || (year < 1) ||
            (month == "") || (day == "") || (year == ""))
        result = -1
    else if (((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30))
        result = -1;
    else {
        if (month == 2) {
            if (day > 29) {
                result = -1;
            }
            else if ((day > 28) && (!leapyear(year))) {
                result = -1;
            }
        }
        else if ((year > 9999) || (year < 0))
            result = -1;
    }
    if (result == 0) {
        var days = new Date();
        var gdate = days.getDate();
        var gmonth = days.getMonth();
        var gyear = days.getFullYear();
        var age = gyear - year;
        if ((month == (gmonth + 1)) && (day <= parseInt(gdate))) {
            age = age;
        }
        else {
            if (month <= (gmonth)) {
                age = age;
            }
            else {
                age = age - 1;
            }
        }
        if (age == 0) {
            age = age;
        }
        result = age;
    }
    return result;
}

function setAttribute(attributeName, attributeValue, owner) {
    var newAttribute = document.createAttribute(attributeName);
    newAttribute.value = attributeValue;
    owner.attributes.setNamedItem(newAttribute);
}

function RequestDataFromService(s) {
    var scriptElement = document.createElement('script');

    var typeAttribute = document.createAttribute('type');
    typeAttribute.value = 'text/javascript';
    scriptElement.attributes.setNamedItem(typeAttribute);

    var languageAttribute = document.createAttribute('language');
    languageAttribute.value = 'javacript';
    scriptElement.attributes.setNamedItem(languageAttribute);

    var sourceAttribute = document.createAttribute('src');
    sourceAttribute.value = s;
    scriptElement.attributes.setNamedItem(sourceAttribute);

    var documentHead = document.getElementsByTagName('head')[0];
    documentHead.appendChild(scriptElement);
}

function getAjaxDate(dateString) {
    var temp = '"' + dateString.replace(new RegExp('/', 'g'), '\\/') + '"';
    return Sys.Serialization.JavaScriptSerializer.deserialize(temp);
}

var days = new Array(new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"),
                     new Array("dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"));
var months = new Array(new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "Octomber", "November", "December"),
                       new Array("janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"));
var m_zodiacSigns = new Array(new Array("Capricorn", "Aquarius", "Pisces", "Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittaire", "Unspecified"),
                              new Array("Capricorne", "Verseau", "Poissons", "Bélier", "Taureau", "Gémeaux", "Cancer", "Lion", "Vierge", "Balance", "Scorpion", "Sagittaire", "non spécifié"));

var m_maritalStatus = new Array(new Array("Unspecified", "Single", "In a relationship", "Engaged", "Married", "Divorced"),
                                new Array("non spécifié", "Célibataire", "Vivant en couple", "Engaged", "Marrié(e)", "C'est compliqué"));

function getDateString(datetime, language) {
    var year = datetime.getYear() % 100;
    return  days[language][datetime.getDay()] + " " + 
            datetime.getDate() + " " + 
            months[language][datetime.getMonth()] + " " + 
            (year < 10 ? "0" + year : year);
}

function getMaritalStatus(maritalCode, language) {
    return m_maritalStatus[language][maritalCode];
}

function getZodiacSign(birthDate, language) {
    var signID;
    var day = birthDate.getDate();
    var month = birthDate.getMonth();
    var year = birthDate.getFullYear();
    
    // Chack if the date was not specified
    if (year == 1900 && month == 0 && day == 1)
    {
        signID = 12;
    }
    else
    {
        if (month == 0 && day <= 19) {
            signID = 0;
        }
        if (month == 0 && day >= 20) {
            signID = 1;
        }
        if (month == 1 && day <= 18) {
            signID = 1;
        }
        if (month == 1 && day >= 19) {
            signID = 2;
        }
        if (month == 2 && day <= 20) {
            signID = 2;
        }
        if (month == 2 && day >= 21) {
            signID = 3;
        }
        if (month == 3 && day <= 20) {
            signID = 3;
        }
        if (month == 3 && day >= 21) {
            signID = 4;
        }
        if (month == 4 && day <= 20) {
            signID = 4;
        }
        if (month == 4 && day >= 21) {
            signID = 5;
        }
        if (month == 5 && day <= 20) {
            signID = 5;
        }
        if (month == 5 && day >= 21) {
            signID = 6;
        }
        if (month == 6 && day <= 21) {
            signID = 6;
        }
        if (month == 6 && day >= 22) {
            signID = 7;
        }
        if (month == 7 && day <= 21) {
            signID = 7;
        }
        if (month == 7 && day >= 22) {
            signID = 8;
        }
        if (month == 8 && day <= 21) {
            signID = 8;
        }
        if (month == 8 && day >= 22) {
            signID = 9;
        }
        if (month == 9 && day <= 21) {
            signID = 9;
        }
        if (month == 9 && day >= 22) {
            signID = 10;
        }
        if (month == 10 && day <= 21) {
            signID = 10;
        }
        if (month == 10 && day >= 22) {
            signID = 11;
        }
        if (month == 11 && day <= 20) {
            signID = 11;
        }
        if (month == 11 && day >= 21) {
            signID = 0;
        }
    }

    return m_zodiacSigns[language][signID];
}
 
function setInnerHTML(element, text) {
    var range;
    var docFrag;
    
    if (element.outerHTML) {
        element.outerHTML = text;
    }
    else {
       range = document.createRange();
       range.setStartBefore(element);
       docFrag = range.createContextualFragment(text);
       element.parentNode.replaceChild(docFrag, element);  
    }
}



function iBoxMessagePopupCallback() {
}

// Opens the popup of a friend profile
function openMessagePopup(message, height, width) {
    iBox.clearEventListeners('documentLoad');
    iBox.addEventListener('documentLoad', iBoxMessagePopupCallback);
    iBox.showURL('MessagePopup.aspx?message=' + message, '', { height: height, width: width });
}

/**
* Search_Box behavior
* @author   zytzagoo
* @version  0.2
* @license  http://www.opensource.org/licenses/mit-license.php
* @examples: http://zytzagoo.net/code/search_box_behavior/examples.html
*/
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#999'; // Colour of default text

function Search_Box(cfg) {
    // defaults are always nice
    var defaults = { ELEMENT_ID: 'q', DEFAULT_VALUE: 'inherit', FOCUSED_VALUE: '' };
    if (cfg) {
        // we have a cfg, loop thru the properties
        // and make sure something is not missing
        // if so, add it from the defaults
        for (var name in cfg) {
            if (cfg.hasOwnProperty(name)) {
                for (var defname in defaults) {
                    if (defaults.hasOwnProperty(defname)) {
                        if (!(cfg[defname])) {
                            cfg[defname] = defaults[defname];
                        }
                    }
                }
            }
        }
    } else {
        cfg = defaults;
    }
    /**
    * return a new object literal with extra
    * stuff attached on it
    */
    return {
        /**
        * Checks the element we're working on exists, and
        * attaches handlers to it. Usually called after the document
        * has loaded or (even better but harder to achieve truly
        * cross-browser) when the element referenced by
        * Search_Input.ELEMENT_ID is available in the DOM.
        */
        init: function () {
            var el = document.getElementById(cfg.ELEMENT_ID);
            if (el) {
                /**
                * special case: 'inherit'
                * This resets the passed in default value and
                * if the element has a previously set value, that
                * value is used as the default from now on.
                */
                if (cfg.DEFAULT_VALUE === 'inherit') {
                    cfg.DEFAULT_VALUE = '';
                    if (el.value !== '') {
                        cfg.DEFAULT_VALUE = el.value;
                    }
                }
                /**
                * If a default value is specified, override
                * whatever exists in the value attribute of the input in html
                */

                /**
                * if we have a custom focus handler passed in,
                * attach that one too and make sure it is called first
                */
                if (cfg.focus) {
                    Search_Box.attach_handler(el, 'onfocus', cfg.focus);
                }
                // our own focus handler is always attached
                Search_Box.attach_handler(el, 'onfocus', this.focus);
                /**
                * same as above except this takes care of onblur handlers
                */
                if (cfg.blur) {
                    Search_Box.attach_handler(el, 'onblur', cfg.blur);
                }
                // our own onblur handler is also always attached
                Search_Box.attach_handler(el, 'onblur', this.blur);
                /**
                * in case the elem has no current value,
                * set it to the specified default
                */
                if (el.value === '' && (cfg.DEFAULT_VALUE && cfg.DEFAULT_VALUE !== '')) {
                    el.style.color = inactive_color;
                    el.value = cfg.DEFAULT_VALUE;
                }
            } else {
                throw new Error('Search_Box.init: element (id: "' + cfg.ELEMENT_ID + '") doesn\'t exist');
            }
        },
        /**
        * Handles the onfocus event of the element
        */
        focus: function (e) {
            // delegate, passing in the event object
            var t = Search_Box.get_target(e);
            // if the target of the event is an input element
            if (t.nodeName.toLowerCase() === 'input' || t.nodeName.toLowerCase() === 'textarea') {
                // if the value of that input is empty or default
                if (t.value === cfg.DEFAULT_VALUE || t.value === '') {
                    // set the value to the specified focused value
                    t.style.color = active_color;
                    t.value = cfg.FOCUSED_VALUE;
                    /**
                    * if the now set focused value is not empty
                    * select the contents of the box
                    */
                    if (t.value !== '') {
                        t.select();
                    }
                }
            }
            return true;
        },
        /**
        * Handles the onblur event of the element
        */
        blur: function (e) {
            // delegate, passing in the event object!
            var t = Search_Box.get_target(e);
            // if the target of the event is an input element
            if (t.nodeName.toLowerCase() === 'input' || t.nodeName.toLowerCase() === 'textarea') {
                /**
                * if the current value of that element is the
                * focused value or empty, set the current
                * value to the specified default value
                */
                if (t.value === cfg.FOCUSED_VALUE || t.value === '') {
                    t.style.color = inactive_color;
                    t.value = cfg.DEFAULT_VALUE;
                }
            }
            return true;
        }
    };
}

/**
* Gets the target of an event
*/
Search_Box.get_target = function (x) {
    x = x || window.event;
    return x.target || x.srcElement;
};
/**
* Attaches event handlers to an existing object.
* If an existing handler is found, it is executed before
* our newly attached handler
*/
Search_Box.attach_handler = function (o, evt, f) {
    if (o !== null) {
        var existing_handler = o[evt];
        if (typeof o[evt] !== 'function') {
            /**
            * no previous handler found
            * TODO: this might need looking into,
            * but it seems to work so far...
            */
            o[evt] = f;
        } else {
            /**
            * Previous handler found, invoke it,
            * while making sure that the 'this' keyword
            * inside the handler function refers to the
            * input element.
            * This enables some cool custom onfocus and
            * onblur handlers possible and logical and
            * easy to develop and not worry about naming
            * stuff...
            */
            o[evt] = function (e) {
                existing_handler.apply(o, arguments);
                f.apply(o, arguments);
            };
        }
    }
};

function flagImageMissing(flagImg)
{
    setAttribute('src', 'images/flags/NoFlag.png', flagImg);
}
