﻿/*
Generic extensions to the JavaScript API
*/

Array.prototype.contains = function(obj, equality) {
    for (var i = 0; i < this.length; i++) {
        if (equality) {
            return equality(this[i], obj);
        }
        else if (this[i] == obj) {
            return true;
        }
    }
    return false;
};

Array.ensureArray = function(obj) {
    if (Object.prototype.toString.call(obj) === '[object Array]') {
        return obj;
    } else {
        return [obj];
    }
};

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}

/*
Volvo.CWP global object. 
Add new static functions as:
Volvo.CWP.functionName = function(args) { };

Add a new class as:
Volvo.CWP.className = function(constructorArgs) { constructor logic };
Volvo.CWP.className.prototype.methodName = function(args) { };
*/
var Volvo = function() { };
Volvo.CWP = function() { };

Volvo.CWP.createDelegate = function(context, method) {
    return (function() {
        method.apply(context, arguments);
    });
};

Volvo.CWP.openWin = function(anchor, siteExitAlert, windowParams) {
    var url = anchor.href;
    var name = anchor.target || '_new';
//    if (siteExitAlert) {
//        alert('site exit alert goes here');
//    }
    window.open(url, name, windowParams);
};

Volvo.CWP.containsElement = function(parent, searchFor) {
    while (searchFor.parentNode) {
        if (searchFor == parent) {
            return true;
        }
        if (!searchFor.parentNode) {
            return false;
        }
        searchFor = searchFor.parentNode;
    }
    return false;
};

/* begin PageManager */
Volvo.CWP.getPageManager = function() {
    if (!Volvo.CWP._currentPageManager) {
        Volvo.CWP._currentPageManager = new Volvo.CWP.PageManager();
    }
    return Volvo.CWP._currentPageManager;
};

Volvo.CWP.PageManager = function() {
    this._managedPanels = new Array();
    this._beginRequestHandlers = new Array();

    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(
        Volvo.CWP.createDelegate(this, this.handlePageLoaded)
    );
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(
        Volvo.CWP.createDelegate(this, this.handleBeginRequest)
    );
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
        Volvo.CWP.createDelegate(this, this.handleEndRequest)
    );
};

Volvo.CWP.PageManager.prototype.addBeginAsyncRequest = function(func) {
    this._beginRequestHandlers.push(func);
};

Volvo.CWP.PageManager.prototype.showMask = function(panelID) {
    if (this._managedPanels) {
        for (var i = 0; i < this._managedPanels.length; i++) {
            if (this._managedPanels[i].ID == panelID && this._managedPanels[i].ShowMask) {
                return true;
            }
        }
    }
    return false;
};

Volvo.CWP.PageManager.prototype.handlePageLoaded = function(sender, args) {
    if (this._managedPanels) {
        for (var i = 0; i < this._managedPanels.length; i++) {
            var managedPanel = document.getElementById(this._managedPanels[i].ID.replace(/\$/g, '_'));
            if (managedPanel == null) {
                continue;
            }
            var divs = YAHOO.util.Dom.getElementsByClassName('updatepanelmask', managedPanel);
            if (divs.length > 0) {
                divs[0].style.display = 'none';
            }
            else {
                if (this._managedPanels[i].ShowMask) {
                    this.createUpdateMask(managedPanel);
                }
            }
        }
    }
};

Volvo.CWP.PageManager.prototype.handleBeginRequest = function(sender, args) {
    var updatePanels = sender._postBackSettings.panelID.split('|');
    for (var i = 0; i < this._beginRequestHandlers.length; i++) {
        this._beginRequestHandlers[i](updatePanels);
    }
    for (var i = 0; i < updatePanels.length; i++) {
        var id = updatePanels[i];
        if (this.showMask(id)) {
            var updatePanel = document.getElementById(id.replace(/\$/g, '_'));
            if (updatePanel == null) {
                continue;
            }
            var panelmask = null;
            var divs = YAHOO.util.Dom.getElementsByClassName('updatepanelmask', updatePanel);
            if (divs.length > 0) {
                panelmask = divs[0];
            }
            else {
                if (this._managedPanels[i].ShowMask) {
                    panelmask = this.createUpdateMask(updatePanel);
                }
            }
            if (panelmask) {
                panelmask.style.display = 'block';
            }
        }
    }
};

Volvo.CWP.PageManager.prototype.handleEndRequest = function(sender, args) {
    var updatePanels = sender._postBackSettings.panelID.split('|');
    for (var i = 0; i < updatePanels.length; i++) {
        var updatePanel = document.getElementById(updatePanels[i].replace(/\$/g, '_'));
        if (updatePanel == null) {
            continue;
        }
        var scripts = updatePanel.getElementsByTagName('script');
        for (var j = 0; j < scripts.length; j++) {
            eval(scripts[j].innerHTML);
        }
    }
};

Volvo.CWP.PageManager.prototype.createUpdateMask = function(panel) {
    var mask = document.createElement('div');
    mask.className = 'updatepanelmask';
    mask.style.left = YAHOO.util.Dom.getX(panel) - 5;
    mask.style.top = YAHOO.util.Dom.getY(panel);
    mask.style.width = panel.offsetWidth + 10;
    mask.style.height = panel.offsetHeight;
    panel.appendChild(mask);
    mask.innerHTML = '<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td height="100%" width="100%" align="center" valign="middle"><img src="/_layouts/cwp/images/ajax-loader.gif" /></td></tr></table>';
    return mask;
};

Volvo.CWP.PageManager.prototype.registerManagedPanel = function(panel) {
    this._managedPanels.push(panel);
};

/* end PageManager */

/* begin ManagedPanel */

Volvo.CWP.ManagedPanel = function(panelID, showMask) {
    this.ID = panelID;
    this.ShowMask = showMask;
    Volvo.CWP.getPageManager().registerManagedPanel(this);
};

/* end ManagedPanel */

/* begin Accordion */
/*
Accordion takes an element or an ID in the constructor
Optionally also takes animation speed (in seconds) for expanding
and collapsing, respectively. Defaults are .2s each.

Has two events:
onselecteditemchanging fires when the selected index has changed but before the accordion has moved
onselecteditemchanged fires after the accordion has finished moving
*/
Volvo.CWP.Accordion = function(ele, options) {
    if (ele.nodeName) {
        this.ul = ele;
    } else {
        this.ul = document.getElementById(ele);
    }
    this.options = options;
    this.init();
};

Volvo.CWP.Accordion.prototype.init = function() {
    this.ensureOptionsValues();
    this.onselecteditemchanging = new YAHOO.util.CustomEvent('onselecteditemchanging');
    this.onselecteditemchanged = new YAHOO.util.CustomEvent('onselecteditemchanged');
    this.items = new Array();
    for (var i = 0; i < this.ul.childNodes.length; i++) {
        var li = this.ul.childNodes[i];
        if (li.nodeName.toUpperCase() != 'LI') {
            continue;
        }
        var headitem = YAHOO.util.Dom.getElementsByClassName('head-item', 'div', li)[0];
        headitem.style.cursor = 'pointer';

        var link = headitem.firstChild;
        while (link != null && link.nodeName != 'A') {
            link = link.nextSibling;
        }
        if (link != null) {
            link.onclick = Volvo.CWP.createDelegate(this, this.handleClick);
        } else {
            headitem.onclick = Volvo.CWP.createDelegate(this, this.handleClick);
        }


        li.style.overflow = 'hidden';
        if (this.items.length > 0) {
            li.style.height = headitem.offsetHeight + 'px';
        }
        this.items.push(li);
    }
    this.activeIndex = this.options.startIndex;
    this.setActiveItem(this.activeIndex);
};

Volvo.CWP.Accordion.prototype.handleClick = function(e) {
    var sender = e && e.target || window.event.srcElement;

    var index = -1;
    for (var i = 0; i < this.items.length; i++) {
        if (Volvo.CWP.containsElement(this.items[i], sender)) {
            index = i;
            break;
        }
    }
    if (index > -1) {
        if (index != this.activeIndex) {
            this.setActiveItem(index);
        } else if (this.options.allowCollapse) {
            this.closeActiveItem();
        } else {
            return true;
        }
    }
    if (window.event) {
        window.event.returnValue = false;
    }
    return false;
};

Volvo.CWP.Accordion.prototype.getCollapsedHeight = function(item) {
    return YAHOO.util.Dom.getElementsByClassName('head-item', 'div', item)[0].offsetHeight;
};

Volvo.CWP.Accordion.prototype.getExpandedHeight = function(item) {
    return YAHOO.util.Dom.getElementsByClassName('sub-item', 'div', item)[0].offsetHeight + this.getCollapsedHeight(item);
};

Volvo.CWP.Accordion.prototype.setActiveItem = function(index) {
    var currentItem = this.items[this.activeIndex];
    var currentAnim = new YAHOO.util.Anim(currentItem, { height: { to: this.getCollapsedHeight(currentItem)} }, this.options.speed.collapse);
    var newItem = this.items[index];
    var newAnim = new YAHOO.util.Anim(newItem, { height: { to: this.getExpandedHeight(newItem)} }, this.options.speed.expand);
    var prevIndex = this.activeIndex;
    this.activeIndex = index;
    this.onselecteditemchanging.fire({ index: index, previous: prevIndex, accordion: this });
    YAHOO.util.Dom.removeClass(currentItem, 'active');
    YAHOO.util.Dom.addClass(newItem, 'active');
    newAnim.onComplete.subscribe(Volvo.CWP.createDelegate(this, function() { this.onselecteditemchanged.fire({ index: index, previous: prevIndex, accordion: this }); }));
    currentAnim.animate();
    newAnim.animate();
};

Volvo.CWP.Accordion.prototype.closeActiveItem = function() {
    var currentItem = this.items[this.activeIndex];
    var currentAnim = new YAHOO.util.Anim(currentItem, { height: { to: this.getCollapsedHeight(currentItem)} }, this.options.speed.collapse);
    var prevIndex = this.activeIndex;
    this.activeIndex = -1;
    this.onselecteditemchanging.fire({ index: -1, previous: prevIndex, accordion: this });
    YAHOO.util.Dom.removeClass(currentItem, 'active');
    currentAnim.onComplete.subscribe(Volvo.CWP.createDelegate(this, function() { this.onselecteditemchanged.fire({ index: -1, previous: prevIndex, accordion: this }); }));
    currentAnim.animate();
};

Volvo.CWP.Accordion.prototype.ensureOptionsValues = function() {
    if (!this.options) {
        this.options = {};
    }
    if (this.options.speed == undefined) {
        this.options.speed = { expand: .2, collapse: .2 };
    }
    if (this.options.allowCollapse == undefined) {
        this.options.allowCollapse = false;
    }
    if (this.options.startIndex == undefined) {
        this.options.startIndex = 0;
    }
};

/* begin QueryString */

Volvo.CWP.QueryString = function() {
    this.data = [];
}

Volvo.CWP.QueryString.prototype.Read = function() {
    var aPairs, aTmp;
    var queryString = new String(window.location.search);
    queryString = queryString.substr(1, queryString.length); //remove "?"
    aPairs = queryString.split("&");

    for (var i = 0; i < aPairs.length; i++) {
        aTmp = aPairs[i].split("=");
        this.data[aTmp[0]] = aTmp[1];
    }
}

Volvo.CWP.QueryString.prototype.GetValue = function(key) {
    return this.data[key];
}

Volvo.CWP.QueryString.prototype.SetValue = function(key, value) {
    if (value == null)
        delete this.data[key];
    else
        this.data[key] = value;
}

Volvo.CWP.QueryString.prototype.ToString = function() {
    var queryString = new String("");

    for (var key in data) {
        if (queryString != "")
            queryString += "&"
        if (this.data[key])
            queryString += key + "=" + this.data[key];
    }
    if (queryString.length > 0)
        return "?" + queryString;
    else
        return queryString;
}
Volvo.CWP.QueryString.prototype.Clear = function() {
    // delete this.data;
    this.data = [];
}

/* end QueryString */

/* begin Cookies */
Volvo.CWP.Cookies = function Cookies() {
    this.cookieData = [];
}
Volvo.CWP.Cookies.prototype.Read = function() {
    var pairs = new String(window.document.cookie).split(";");
    var tmp, cookieName, keyName;
    for (var i = 0; i < pairs.length; i++) {
        tmp = pairs[i].split("=");

        if (tmp.length == 3) {
            cookieName = new String(tmp[0]);
            cookieName = cookieName.replace(" ", "");

            if (cookieData[cookieName] == null)
                cookieData[cookieName] = [];
            cookieData[cookieName][tmp[1]] = unescape(tmp[1]);
        }
        else //length = 2
        {
            keyName = tmp[0];
            keyName = keyName.replace(" ", "");
            if (keyName.substring(0, 12) != "ASPSESSIONID") {
                if (cookieData[""] == null)
                    cookieData[""] = [];
                cookieData[""][keyName] = unescape(tmp[1]);
            }
        }
    }

}

Volvo.CWP.Cookies.prototype.GetValue = function(cookie, key) {
    if (this.cookieData[cookie] != null)
        return this.cookieData[cookie][key];
    else
        return null;
}
Volvo.CWP.Cookies.prototype.SetValue = function(cookie, key, value) {
    if (this.cookieData[cookie] == null)
        this.cookieData[cookie] = [];
    this.cookieData[cookie][key] = value;
}
Volvo.CWP.Cookies.prototype.Write = function() {

    var toWrite;
    var thisCookie;
    var expireDateKill = new Date();
    var expireDate = new Date();
    expireDate.setYear(expireDate.getFullYear() + 10);
    expireDateKill.setYear(expireDateKill.getFullYear() - 10);


    var pairs = new String(window.document.cookie).split(";");
    var tmp, cookieName, keyName;
    for (var i = 0; i < pairs.length; i++) {
        tmp = pairs[i].split("=");
        if (tmp.length == 3) {
            window.document.cookie = tmp[0] + "=" + tmp[1] + "='';expires=" + expireDateKill.toGMTString();
        }
        else {
            keyName = tmp[0];
            keyName = keyName.replace(" ", "");
            if (keyName.substring(0, 12) != "ASPSESSIONID")
                window.document.cookie = keyName + "='';expires=" + expireDateKill.toGMTString();
        }
    }

    for (var cookie in cookieData) {
        toWrite = "";
        thisCookie = this.cookieData[cookie];
        for (var key in thisCookie) {
            if (thisCookie[key] != null) {
                if (cookie == "")
                    toWrite = key + "=" + thisCookie[key];
                else
                    toWrite = cookie + "=" + key + "=" + escape(thisCookie[key]);
                toWrite += "; expires=" + expireDate.toGMTString();
                window.document.cookie = toWrite;
            }
        }
    }
}

/* end Cookies */

Volvo.CWP.SetSelectValue = function(SelectObject, Value) {
    for (index = 0;
            index < SelectObject.length;
            index++) {
        if (SelectObject[index].value == Value)
            SelectObject.selectedIndex = index;
    }
}

Volvo.CWP.LinkableTextBox = function(updatePanelID) {
    //Volvo.CWP.LinkableTextBox._items.push(updatePanelID);
    this._updatePanelID = updatePanelID;
    this._inputFields = document.getElementById(updatePanelID.replace(/\$/g, '_')).getElementsByTagName('input');

    //if (Volvo.CWP.LinkableTextBox._items.length < 1) {
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(
        Volvo.CWP.createDelegate(this, this.handleBeginRequest)
    );
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
        Volvo.CWP.createDelegate(this, this.handleEndRequest)
    );
    //}
};

//Volvo.CWP.LinkableTextBox._items = new Array();

Volvo.CWP.LinkableTextBox.prototype.handleBeginRequest = function(sender, args) {
    var updatePanels = sender._postBackSettings.panelID.split('|');
    for (var i = 0; i < updatePanels.length; i++) {
        var id = updatePanels[i];
        if (this._updatePanelID == id) {
            for (var j = 0; j < this._inputFields.length; j++) {
                this._inputFields[j].disabled = true;
            }
        }
    }
};

Volvo.CWP.LinkableTextBox.prototype.handleEndRequest = function(sender, args) {
    var updatePanels = sender._postBackSettings.panelID.split('|');
    for (var i = 0; i < updatePanels.length; i++) {
        var id = updatePanels[i];
        if (this._updatePanelID == id) {
            for (var j = 0; j < this._inputFields.length; j++) {
                this._inputFields[j].disabled = false;
            }
        }
    }
};

function NameValueCollection() { }

NameValueCollection.prototype.getLength = function() {
    var len = -2;
    for (property in this) {
        len++;
    }
    return len;
};

NameValueCollection.prototype.getItem = function(index) {
    var len = -1;
    for (property in this) {
        if (len == index) {
            return this[property];
        }
        len++;
    }
    return null;
};
var handleToggleTextBox = function(e){
    var img = $(e.target);
    var lbl = img.parent().find('span').first();
    var txt = img.parent().find('input').first();
    if(lbl.is(':hidden')) {
        img.parent().find('.warning').remove();
        if(txt.val() == '') {
            img.parent().append($('<span class=\'warning ms-input\' style=\'color:red;\'>*</span>'));
            return;
        } else {
            img.parent().find('.warning').remove();
        }
        lbl.show();
        lbl.text(txt.val());
        txt.hide();
        img.attr('src','/_layouts/images/cmseditsourcedoc.gif');
    } else {
        txt.show();
        lbl.hide();
        img.attr('src','/_layouts/images/cnsapp16.gif');
    }
};