﻿// Augment native types.
Array.prototype.copy = function() {
    var shallowCopy = [],
    i;

    for (i = 0; i < this.length; i++) {
        shallowCopy[i] = this[i];
    }

    return shallowCopy;
}

Array.prototype.contains = function(element) {
    var x;
    for (x in this) {
        if (x === element) {
            return true;
        }
    }
    
    return false;
}


String.prototype.startsWith = function(substring) {
    /// <summary>Returns true if this instance starts with the substring; otherwise, false.</summary>
    return (this.indexOf(substring) === 0);
}

var adecco = {};

adecco.getCookie = function(cookieName) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(cookieName + "=");
        if (c_start != -1) {
            c_start = c_start + cookieName.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return decodeURIComponent(document.cookie.substring(c_start, c_end));
        }
    }
    return '';
}

adecco.setCookie = function(cookieName, value, expiredays, path) {
    var 
        expirationDate = new Date()
        , expires
        , path;

    // Set the expiration date
    expirationDate.setDate(expirationDate.getDate() + expiredays);
    expires = (expiredays == null) ? '' : ';expires=' + expirationDate.toUTCString();

    // Set the path (default to "/")
    path = ';path=' + (path || '/');

    document.cookie = cookieName + '=' + encodeURIComponent(value) + expires + path;
}

adecco.QueryString = function() {
    this._rawQueryString = window.location.search.substring(1); // remove the heading "?"
    this._params = {};

    var pairs = this._rawQueryString.split('&');
    for (var i = 0; i < pairs.length; i++) {
        var keyValue = pairs[i];
        var idxEqual = keyValue.indexOf('=');

        if (idxEqual > 0) {
            // Add the pair to the params.
            //Fixed BUG id DE3422- 05-11-2011 - encoded the ulr and convert '+' into space
            this._params[keyValue.substring(0, idxEqual)] = encodeURIComponent(keyValue.substring(idxEqual + 1)).replace(/%2B/g, ' ');
            //keyValue.substring(idxEqual + 1); -> for some reason json ajax call converts '+' to %2B.
        }
    }
}

adecco.QueryString.prototype.getValue = function(key, defaultValue) {
    var value = this._params[key];
    if (value == null) {
        value = defaultValue;
    }

    return value;
}

adecco.QueryString.prototype.setValue = function(key, value) {
    this._params[key] = value;
}


adecco.QueryString.prototype.make = function() {
    var queryString = [], prop;
    for (key in this._params) {
        if (this._params.hasOwnProperty(key)) {
            queryString.push(escape(key) + '=' + escape(this._params[key]));
        }
    }

    return '?' + queryString.join('&');
}

adecco.QueryString.prototype.go = function() {
    window.location.href = location.pathname + this.make();
}

adecco.getValueForPath = function(obj, path) {
    if (typeof (path) !== 'string') {
        return undefined;
    }

    if (path.indexOf('.') < 0) {
        return obj[path];
    }

    // Iterate over the object graph.
    var splitPath = path.split('.');
    for (var i = 0; i < splitPath.length; i++) {
        obj = obj[splitPath[i]];

        if (typeof (obj) === 'undefined' || obj === null) {
            return null;
        }
    }

    return obj;
}


adecco.Logger = function() {
    this._history = [];
};

adecco.Logger.prototype.logDebug = function(value) {
    //alert(value);
    this._history.push(value);
};

window.logger = new adecco.Logger();

/*window.log = function(value) {
    window.logger.logDebug(value);
}*/

adecco.showContentInPopover = function(content, options) {
    var stringBuilder = [], popopverContent, popover;

    options = options || {};

    // First we drop any existing pop-over
    //$('.pop-over').remove();

    var leftAligned = false;
    var rightAligned = false;

    //alert($('.set-location-popover').width());

    // Temp hack: appending an empty div to get the width of the .set-location-popver as there are no instances at this point
    $('body').append('<div class="set-location-popover toberemoved" />');

    //alert('right al: ' + ((options.x - ($('.set-location-popover').width() / 2));
    //alert('left al: ' + ((options.x + ($('.set-location-popover').width() / 2)));
    if ((options.x - ($('.set-location-popover').width() / 2)) < 15) { leftAligned = true; }
    if ((options.x + ($('.set-location-popover').width() / 2)) > ($(document).width() - 10)) { rightAligned = true; }

    // remove the div added above
    $('.toberemoved').remove();
    
    //    alert('left al: ' + leftAligned + ', right al: ' + rightAligned);
    stringBuilder.push('<div id="pop-over" class="pop-over" >');
    stringBuilder.push('<table>');
    stringBuilder.push('    <tr class="top">');
    stringBuilder.push('        <td class="left"></td>');
    if (!leftAligned && !rightAligned) {
        stringBuilder.push('        <td class="middle">');
        stringBuilder.push('          <div class="flyout-icon" style="width : 20px; margin: 0pt auto;">&nbsp;</div>');
    }
    if (rightAligned) {
        stringBuilder.push('        <td class="middle">');
        stringBuilder.push('          <div class="flyout-icon" style="width : 20px; margin-left: auto; margin-right: 0pt;">&nbsp;</div>');
    }
    if (leftAligned) {
        stringBuilder.push('        <td class="middle" style="margin-left: 0pt; margin-right: auto;">');
        stringBuilder.push('          <div class="flyout-icon">&nbsp;</div>');
    }
    stringBuilder.push('        </td>');
    stringBuilder.push('        <td class="right"></td>');
    stringBuilder.push('    </tr>');
    stringBuilder.push('    <tr class="middle">');
    stringBuilder.push('        <td class="left"></td>');
    stringBuilder.push('        <td class="middle popover-content">');

    // Add content if it's a plain string; otherwise, will be added later.
    if (typeof (content) === 'string') {
        stringBuilder.push(content);
    }

    stringBuilder.push('        </td>');
    stringBuilder.push('        <td class="right"></td>');
    stringBuilder.push('    </tr>');
    stringBuilder.push('    <tr class="bottom">');
    stringBuilder.push('        <td class="left"></td>');
    stringBuilder.push('        <td class="middle"></td>');
    stringBuilder.push('        <td class="right"></td>');
    stringBuilder.push('    </tr>');
    stringBuilder.push('</table>');
    stringBuilder.push('</div>');


    popopverContent = stringBuilder.join('');
    popover = $(popopverContent);

    if (options.className) {
        popover.addClass(options.className);
    }

    // Add the content.
    if (typeof (content) !== 'string') {
        $('.popover-content', popover).append(content);
    }

    $('body').append(popover);

    // Position the popup
    if (typeof (options.x) !== 'undefined') {
        if (!leftAligned && !rightAligned) {
            popover.css({ position: 'absolute', left: (options.x - popover.width() / 2) });
        }
        if (rightAligned) {
            popover.css({ position: 'absolute', left: (options.x - popover.width() + $('.right', popover).width()) });
        }
        if (leftAligned) {
            popover.css({ position: 'absolute', left: (options.x - $('.left', popover).width()) });
        }


        if (typeof (options.y) !== 'undefined') {
            popover.css('top', options.y);
        }
    }

    return popover;
}

// Register NullLogger if BlackbirdJS logger isn't there
window.log = window.log || {
    debug: function() { },
    info: function() { },
    warn: function() { },
    error: function() { }
}

window.onerror = function(message, url, line) {
    log.error(url + ' @ line ' + line + '<br/>  ' + message);
    //return true;
}

////window.onerror = function(a, b, c, d, e, f) {
////    debugger;
////}

/// <summary>Provides a mechanism for broadcasting information within a window.
/// It is essentially a notification dispatch table.</summary>

adecco.NotificationCenter = {
    __notificationTable: {},


    addObserver: function(observer, callback, notificationName, notificationSender) {

        // If this notification doesn't exist, create it.
        if (!this.__notificationTable[notificationName]) {
            this.__notificationTable[notificationName] = [];
        }

        var notifyList = this.__notificationTable[notificationName];

        // Only add observer if it's not already registered (to avoid multiple notifications of the same event).
        if (!notifyList.contains(observer)) {
            notifyList.push({ observer: observer, callback: callback });
        }
    },

    postNotificationName: function(notificationName, notificationSender, userInfo) {
        var 
            observerPair, i,
            notifyList = this.__notificationTable[notificationName] || [];

        for (i = 0; i < notifyList.length; i++)
        {
            observerPair = notifyList[i];
            if (!observerPair || !observerPair.observer) {
                // TODO: clean up observer
            } else {
                observerPair.callback.apply(observerPair.observer, [notificationSender, userInfo]);
            }
        }
    }
};
