///Wadja Javascript framework
///Version 1.0, last build: 20072010

//#Public vars for global.js
var PreviewTimeout = '';//#used by create/edit label-preview label name

window.addEvent('domready', function () {
    //#Hover-craft bio info
    var bioHover;

    if ($('bio_hovercraft')) {
        bioHover = $('bio_hovercraft');
        bioHover.set('opacity', 0);
    }

    if ($('contact_name_over')) {
        $('contact_name_over').addEvents({
            'mouseenter': function () {
                bioHover.setStyle('display', 'block').fade('in');
                bioHover.setStyles({
                    top: '52px',
                    zindex: '1000',
                    width: '287px',
                    left: '2px'
                });
                //top:70px;width:280px;z-index: 9999;
            }
        });
    }
    if ($('bio_hovercraft')) {
        $('bio_hovercraft').addEvents({
            'mouseleave': function () {
                bioHover.fade('out');
                bioHover.setStyles({
                    zindex: '-1'
                });
            },
            'click': function () {
                bioHover.fade('out');
                bioHover.setStyles({

                    zindex: '-1'
                });
                //top.location.href = '/'+ profileInfo.ownerWadjaID+'#!My/8/1';
            },
            'mouseenter': function () {
                bioHover.setStyle('display', 'block').fade('in');
                bioHover.setStyles({
                    top: '52px',
                    zindex: '1000',
                    width: '287px',
                    left: '2px'
                });
                //top:70px;width:280px;z-index: 9999;
            }
        });
    }

    $$('a.share').each(function (a) {
        //containers 
        var storyList = a.getParent();
        var shareHover = storyList.getElements('div.share-hover')[0];

        shareHover.set('opacity', 0);
        //show/hide 
        a.addEvent('mouseenter', function () {
            shareHover.setStyle('display', 'block').fade('in');
            if (a.get('id') == 'topPoints') {
                if ($('points_hovercraft')) {
                    //#ajax call
                    var wjxGetUsrPoints = new WADJAX('User', { statusBar: false });
                    try {
                        wjxGetUsrPoints.send('GetPoints', profileInfo.viewerID, function (res) {
                            if (res.error) return;
                            else
                                $('points_hovercraft').set('html', res.value);
                        });
                    }
                    catch (Error) { alert('share-points info: ' + Error); }
                }
            }
        });

        shareHover.addEvent('mouseleave', function () {
            shareHover.fade('out');
        });

        storyList.addEvent('mouseleave', function () {
            shareHover.fade('out');
        });
    });
})

//global vars
var currentDropdown = ''; //0:all dropdowns close

/// Search public variables
var Search = {
    Type: '',
    SetType: function (searchType) {
        if ($('text_search')) {
            if (searchType != '') {
                $('text_search').value = searchType + ': ';
            }
            else {
                $('text_search').value = searchType;
            }
            $('text_search').focus();
        }
        if ($('SearchDropdown'))
            $('SearchDropdown').addClass('dndD')
        this.Type = searchType.toLowerCase();
    },
    // Search Function (redirects to profile page to display results)
    GlobalSearch: function (toSearchFor) {
        var keyword = toSearchFor.trim();
        var category = Search.Type;
        if (keyword.toLowerCase().indexOf(category + ': ') == 0) {
            keyword = keyword.substr((category + ': ').length);
        }
        if (keyword.length > 0) {
            if (profileInfo.ownerID > 0)
                top.location.href = '/' + profileInfo.ownerWadjaID + '#!search?searchType=' + category + '&searchFor=' + keyword;
            else top.location.href = '/wadja#!search?searchType=' + category + '&searchFor=' + keyword;
            if ($('SearchDropdown'))
                $('SearchDropdown').addClass('dndD');
        }
    }
}

///FORMS -
///Description:Handle key-enter, enter to clear text
var FormValidators = {
    handleEnter: function (field, event, action) {
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) {
            ///link
            ///message
            ///call function
            return false;
        }
        else
            return true;
    }
}
///ALERT USER
var Notify = {
    /// Handle top notification bar
    topBarOn: function (Text, BarColor, Delay) {
        try {
            /// add color
            if (BarColor == 'red') {
                if ($('dvNotBar'))
                    $('dvNotBar').addClass('dvNotBarError');
            }
            else {
                if ($('dvNotBar'))
                    $('dvNotBar').removeClass('dvNotBarError');
            }

            /// Add text to display           
            $('dvNotBar').setStyle('display','block');
            /// Reveal effect
            MyElement.reveal('dvNotBar');
            $('dvNotBarText').set('html', Text);
            //An anonymous function which waits x seconds and then fades out
            if (Delay > 0) {
                (function () { new Fx.Reveal($('dvNotBar')).dissolve(); }).delay(Delay * 1000);
                
            }

            /// ---------------
        }
        catch (Error) {
            try {
                Notify.alert('Javascript error', 'Javascript error while using [Notify.topBarOn] #' + Error, 'Ok', 'red');
            }
            catch (ErrorAgain) {
                alert(ErrorAgain);
            }
        }
    },
    /// MARK -
    /// Hide top notification bar
    topBarOff: function (Text, Delay) {
        new Fx.Reveal($('dvNotBar')).dissolve();
    },
    remove: function (Element, Delay) {

        $(Element).setStyle('background-color', '#ecedf2')
        $(Element).tween('opacity', '0.3');

        MyElement.dissolve($(Element));
    },
    /// MARK -
    /// Replace traditional javascript alert message-ok
    alert: function (Title, Message, CancelButtonValue, StyleName) {

        var classTitle = 'faceboxTitleGray';
        var classBorder = 'faceboxGray';

        if (StyleName == 'red') {
            classTitle = 'faceboxTitleRed';
            classBorder = 'faceboxRed';
        }

        var alertBox = new Facebox({
            title: Title,
            message: Message,
            cancelValue: CancelButtonValue,
            classNameTitle: classTitle,
            classNameBorder: classBorder
        });
        alertBox.show();
    },
    /// MARK -
    /// Please wait loading bar
    spinnerOn: function (Text, TextOnDelay, Delay) {
        ///new Fx.Reveal($('dvLoad')).reveal();
        $('dvLoad').removeClass('dnd');
        /// set initial text
        $('spLoad').set('html', Text);
        ///
        $('dvLoad').addClass('loading');
        /// set delay text
        (function () { $('spLoad').set('html', TextOnDelay); }).delay(Delay * 1000);
    },
    /// MARK -
    ///	Hide Please wait loading bar
    spinnerOff: function (Text, Delay) {
        /// dissolve loading
        /// set good bye text
        $('spLoad').set('html', Text);
        ///
        $('dvLoad').removeClass('loading');
        /// hide loading bar-fade out effect
        ///(function () { new Fx.Reveal($('dvLoad')).dissolve(); }).delay(Delay * 1000);
        $('dvLoad').addClass('dnd');
        //new Fx.Reveal($('dvLoad')).dissolve(); 
    }
}
///MY ELEMENTS
var MyElement = {
    /// MARK -
    toggle: function (elementID) {
        $(elementID).toggleClass('dnd');
    },
    toggleD: function (elementID) {
        $(elementID).toggleClass('dndD');
    },
    dissolve: function (elementID) {
        if (navigator.userAgent.indexOf('MSIE') <= 0)
            new Fx.Reveal($(elementID)).dissolve();
        else
            $(elementID).addClass('dnd');
    },
    reveal: function (elementID) {
        if (navigator.userAgent.indexOf('MSIE') <= 0)
            new Fx.Reveal($(elementID)).reveal();
        else
            $(elementID).removeClass('dnd');
    },
    toggleReveal: function (elementID) {
        new Fx.Reveal($(elementID)).toggle();
    },
    fadeIn: function (elementID) {
        $(elementID).fade('in');
    },
    fadeOut: function (elementID) {
        $(elementID).fade('out');
    },
    fadeToggle: function (elementID) {
        $(elementID).fade('toggle');
    },
    slideToggle: function (elementID) {
        //var mySlide = new Fx.Slide(elementID);
        //mySlide.hide();
        //mySlide.toggle();

        if ($(elementID).get('class').indexOf("dnd") > 0)
            $(elementID).removeClass('dnd');
        else
            $(elementID).addClass('dnd');
    },
    misc: function (_options) {
        var options = $extend({
            a: 'Hello a',
            b: 'Hello b'
        }, _options || {});

        this.show = function () {
            alert(options.a + '/' + options.b);
        }
    }
}

/// INFO POP-UPS
var InfoWindow = {
    // Points
    points: function () {
        /// on click do...
        var alertBox = new Facebox({
            title: 'Learn about Wadja points',
            message: '<div class=\'pad10\'>Points are the best way to pay for items on the site. Once you fill your account, you can use them for sending SMS.</div>',
            cancelValue: 'Cancel',
            submitFunction: function () {
                // Dear developer add your ajax code here :)
                // open cart
                alertBox.close();
            },
            //ajaxErrorMessage: message to display when an ajax error occurs.
            //ajaxDelay: minimum time to display the loading message. (In milliseconds. Defaults to 0)
            submitValue: 'Get points',
            submitFocus: 'Yes'//If true, the submit button will be focused. (Pressing enter will activate it)
        });
        alertBox.show();
    },
    getPoints: function (infoTitle, infoMessage) {
        var alertBoxGetpoints = new Facebox({
            title: infoTitle,
            message: '<div class=\'pad10\'>' + infoMessage + '</div>',
            cancelValue: 'Ok',
            footerLink: true, // adds a link before submit buttons
            footerLinkHref: '',
            footerLinkText: 'You have ' + profileInfo.points + ' points'
        });
        alertBoxGetpoints.show();
    },
    usePoints: function (infoTitle, infoMessage) {
        var alertBoxUsepoints = new Facebox({
            title: infoTitle,
            message: '<div class=\'pad10\'>' + infoMessage + '</div>',
            cancelValue: 'Ok',
            footerLink: true, // adds a link before submit buttons
            footerLinkHref: '',
            footerLinkText: 'You have ' + profileInfo.points + ' points'
        });
        alertBoxUsepoints.show();
    }
}

///Handle all credits elements
///Add info pop-up link
///Example: <div class="creditsSp" title="message">Get 2 points</div>
$$('.creditsSp').each(function (element, index) {
    element.addEvent('click', function (event) {
        event.stop();
        /// credits info pop-up
        InfoWindow.getPoints('Learn about Wadja points', element.get('title'));
    });
});

// Handle 'Enter' for search textbox
if ($('text_search')) {
    $('text_search').addEvents({
        keydown: function (event) {
            if (event.key == 'enter') {
                Search.GlobalSearch($('text_search').get('value'));
                return false;
            }
            return true;
        }
    });
}

///DROP DOWN-Effects
var MyMenu = {
    DropDown: function (MenuID, MenuClassName, MenuClassNameActive, DropDownID, DropDownClassName, DropDownClassNameActive) {
        //#Menu - Root
        if ($(MenuID).get('class').indexOf(MenuClassName) >= 0) {
            //#Active
            currentDropdown = MenuID; // set active dropdown
            $(MenuID).removeClass(MenuClassName);
            $(MenuID).addClass(MenuClassNameActive);

        }
        else {
            //#In-active
            currentDropdown = ''; //reset active dropdown
            $(MenuID).removeClass(MenuClassNameActive);
            $(MenuID).addClass(MenuClassName);
        }

        //#Menu - Dropdown values
        if ($(DropDownID).get('class').indexOf('dndD') >= 0) {
            $(DropDownID).removeClass('dndD');
            // Handle My, Follow, Every drop downs
            if ($(MenuID + 'textbox')) {
                $(MenuID + 'textbox').focus();
                $(MenuID + 'textbox').value = '';
            }

            if (MenuID == 'Mylabels') {
                if ($('ulLblMy'))
                    $('ulLblMy').removeClass('dnd');
                if ($('subAllMy'))
                    $('subAllMy').removeClass('dnd');
                if ($('subTrashMy'))
                    $('subTrashMy').removeClass('dnd');
                if ($('subNew'))
                    $('subNew').addClass('dnd');

                //#Load label list
                LabelDropDown('My');
            }
            else if (MenuID == 'Followlabels') {
                if ($('ulLblFollow'))
                    $('ulLblFollow').removeClass('dnd');

                if ($('subAllFollow'))
                    $('subAllFollow').removeClass('dnd');

                //#Load label list
                LabelDropDown('Follow');
            }
            else if (MenuID == 'Everylabels') {

                if ($('ulLblEvery'))
                    $('ulLblEvery').removeClass('dnd');

                if ($('subAllEvery'))
                    $('subAllEvery').removeClass('dnd');

                //#Load label list
                LabelDropDown('Every');
            }
        }
        else {
            $(DropDownID).addClass('dndD');
        }

        MyMenu.hideAll(''); //Hide all other dropdowns

        //#Privacy
        if (MenuID.toLowerCase().trim() == 'privacy') {
            //#use white icons
            var dummy = $('privacyicon').get('class');
            var reW = new RegExp("lblPr.[0-4]", "g");
            var reB = new RegExp("lblPr.[0-4]_b", "g");

            if ($('PrivacyDropdown') && $('PrivacyDropdown').hasClass('dndD')) {  //#use white icons
                //                var mreB = dummy.match(reB);
                //                var nreB = dummy.match(reB)[0].replace('_b', '');

                //                $('privacyicon').set('class', 'hoverNounderline ' + nreB);
            }
            else {  //#use black icons
                if ($('privacyicon')) {
                    var mreW = dummy.match(reW);
                    var nreW = dummy.match(reW)[0] + '_b';
                    $('privacyicon').set('class', 'hoverNounderline ' + nreW);
                }
            }
        }
    },
    hideAll: function (HideDropdown) {
        $$('.dropdown').each(function (element, index) {
            var dropdownFound = element.get('id'); // all dropdowns found

            if (HideDropdown.length > 0) {
                //hide values
                $(HideDropdown + 'Dropdown').addClass('dndD');
                //change to inactive 
                $(HideDropdown).removeClass('active' + hidethis);
                $(HideDropdown).addClass('inactive' + hidethis);
            }
            else if (dropdownFound != currentDropdown) {
                //hide values
                if (dropdownFound.indexOf('feed_pluslabel_dropdown') > 0) {//this for the plus label drop downs
                    $(dropdownFound).addClass('dndD');
                    return;
                }

                if ($(dropdownFound + 'Dropdown')) {

                    $(dropdownFound + 'Dropdown').addClass('dndD');
                    //change to inactive 
                    if (dropdownFound.indexOf('_') < 0) {
                        $(dropdownFound).removeClass('active' + dropdownFound);
                        $(dropdownFound).addClass('inactive' + dropdownFound);
                    }
                    else {

                        var tmpsplit = dropdownFound.split('_')
                        $(dropdownFound).removeClass('active' + tmpsplit[0]);
                        $(dropdownFound).addClass('inactive' + tmpsplit[0]);

                    }
                }



                if ($('PrivacyDropdown') && $('PrivacyDropdown').hasClass('dndD')) {
                    if ($('privacyicon')) {
                        var dummy = $('privacyicon').get('class');
                        //var reB = new RegExp("lblPr.[0-4]_b", "g");
                        //  var nreB = dummy.match(reB)[0].replace('_b', '');
                        $('privacyicon').set('class', dummy.replace("_b", " "));
                    }
                }
            }
            else {


            }
        });
    }
}

/// Hide all drop downs-My,Every,Follow
if ($(document.body)) {
    $(document.body).addEvent(
	'click', function (e) {
	  
	    //Which HTML element is the target of the event?
	    var targ;
	    if (!e) var e = window.event;

	    if (e.target) targ = e.target;
	    else if (e.srcElement) targ = e.srcElement;
	    if (targ.nodeType == 3) // defeat Safari bug
	        targ = targ.parentNode;
	    //

	    if (currentDropdown.length > 0 && currentDropdown != e.target.id) {
	        //arrow: all arrows links, textbox: autocomplete textboxes, privacyicon: privacy icon drop downs
            //#exclude elements from closing the dropdown
	        if (e.target.id.indexOf('Arrow') < 0 && e.target.id.indexOf('group') < 0 && e.target.id.indexOf('textbox') < 0 && e.target.id.indexOf('privacyicon') < 0 && e.target.id.indexOf('lblTop') < 0 && e.target.id.indexOf('currentlbl') < 0) {
	            //debug: alert(e.target.id);
	            $$('.dropdown').each(function (element, index) {
	                var dropdownFound = element.get('id'); // all dropdowns found
	                if (e.target.id != dropdownFound) {
	                    //debug: alert('all '+currentDropdown+'* '+e.target.id);
	                    MyMenu.hideAll('');
	                    currentDropdown = ''; //reset active dropdown
	                }
	            });
	        }
	    }
	});

}


/// Custom on/off buttons
var toggleButtons = {
    OnOff: function (Left, Right) {
        $(Left).removeClass('btn_active');
        $(Right).addClass('btn_active');
    },
    Toggle: function (ToggleBtnId) {
        $(ToggleBtnId).toggleClass('btn_active');
    }
}


/// PLUGINS BELOW THIS LINE
/// ********************************************************************
/// TIPS plugin
/// TIP ON ALL ELEMENTS
/// Element ID, Element_text: text to display, Element_pad: positioning patch
var Tip = {
    doTipOn_: function (elementID, element_text, element_pad) {
        var pos = $(elementID).getCoordinates();
        $('tipit_content').set('html', element_text);
        $('tipit').setStyles({
            top: (pos.top - pos.height) - 5 + 'px',
            left: pos.left + 'px',
            position: 'absolute',
            display: 'block',
            zindex: '100000',
            display: 'block',
            'margin-left':'5px'
        });
        
        $('tipit').addClass('tipsy-north');
        $('tipit').removeClass('tipsy-south');

        $('tipit').addClass('tipsy-up');
        $('tipit').removeClass('tipsy');
        
        $('tipit_content').setStyles({
            display: 'block'
        });
    },
    doTipOnEast:function (elementID, element_text, element_pad) {
        var pos = $(elementID).getCoordinates();
        $('tipit_content').set('html', element_text);
        $('tipit').setStyles({
            top: pos.top - 1 + (pos.height / 2) - (pos.height / 2) + 'px',
            left: pos.left - pos.width + 'px',
            position: 'absolute',
            display: 'block',
            zindex: '100000',
            display: 'block',
            width: '200px'
        });

       
        $('tipit').addClass('tipsy-right');
        $('tipit').removeClass('tipsy');

        $('tipit').removeClass('tipsy-south');
        $('tipit').addClass('tipsy-east');
       
        $('tipit_content').setStyles({
            display: 'block'
        });
    },
    doTipOn: function (elementID, element_text, element_pad) {
        var pos = $(elementID).getCoordinates();
        $('tipit_content').set('html', element_text);
        $('tipit').setStyles({
            top: (pos.top - pos.height) - 10 + 'px',
            left: pos.left + 'px',
            position: 'absolute',
            display: 'block',
            zindex: '100000',
            display: 'block'
        });

        $('tipit_content').setStyles({
            display: 'block'
        });
    },
    doTipOff: function (elementID) {
        $('tipit').setStyles({
            display: 'none'
        });

        $('tipit_content').setStyles({
            display: 'none'
        });
    }
}

/// Get/Set user's language
function setLanguage(lang) {
    var oUserAjax = new WADJAX('User', { statusBar: false });
    try {
        Notify.spinnerOn('Loading...', 'Still loading', 5);
        oUserAjax.send('UpdateLanguage', lang, function (res) {
            if (!res.error) {
                Notify.spinnerOff('done', 1);
                top.location.href = currentUrl;
            }
            else {
                Notify.spinnerOff('done', 1);
                Notify.topBarOn('There was an error', '', 6);
            }
        });
    }
    catch (Error) { alert(Error); }
}

/// Sign out
function SignOut() {
    try {
        var oUserAjax = new WADJAX('User', { statusBar: false });
        Notify.spinnerOn('Loading...', 'Still loading', 5);
        oUserAjax.send('SignOut', function (res) {
            Notify.spinnerOff('done', 1);
            //#overlay preloading
            if ($('overlaymask')) {
                $('overlaymask').removeClass('dnd');
                $('overlaymask_text').set('html','Logging out...');
            }
            top.location.href = '/Default.aspx';
        });
    }
    catch (Error) { alert(Error); }
}
/// Facebox plugin
/*
Facebox for MooTools is a mootools port
from the original Facebox, which was written for jQuery
and which was inspired by the Facebook pop-up messages.
		
Facebox is very extensible, and can be used to display
normal html, images, text fetched with ajax, etc etc.
		
More info and license can be found on http://bertramakers.com/labs/
*/

var Facebox = function (_options) {
    var options = $extend({
        message: 'Message not specified.',
        url: false,
        ajaxErrorMessage: '<h3>Error 404</h3><p>The requested file could not be found.</p>',
        ajaxDelay: 300,
        width: 370,
        height: 'auto',
        title: false,
        draggable: true,
        submitValue: false,
        submitFunction: false,
        submitFocus: false,
        cancelValue: 'Cancel',
        cancelFunction: false,
        loadIcon: '/s3.images/ajax/preloader-big.gif',
        fadeOpacity: .75,
        classNameTitle: 'faceboxTitleGray',
        classNameBorder: 'faceboxGray',
        footerLink: false, // adds a link before submit buttons
        footerLinkHref: '',
        footerLinkText: 'help not specified'

    }, _options || {});

    var box = $(document.createElement("table"));
    box.className = 'facebox';
    var mbox;
    var instance = this;

    this.show = function () {
        for (var i = 0; i < 3; i++) {
            var row = box.insertRow(i);
            for (var a = 0; a < 3; a++) {
                var cell = row.insertCell(a);
                var cellClass = '';
                if (i == 0)
                    cellClass = 'top';
                else if (i == 1)
                    cellClass = 'center';
                else if (i == 2)
                    cellClass = 'bottom';
                if (a == 0)
                    cellClass += 'Left';
                else if (a == 1)
                    cellClass += 'Center';
                else if (a == 2)
                    cellClass += 'Right';
                if (cellClass == "centerCenter") {
                    cell.style.width = options.width + "px";
                    cell.style.height = "auto";
                    mbox = document.createElement("div");
                    mbox.className = 'faceboxContent ' + options.classNameBorder;
                    mbox.style.position = "relative";
                    cell.appendChild(mbox);
                }
                cell.className = cellClass;
            }
        }
        box.style.position = "absolute";
        var boxLeft = (window.getSize().x / 2) + window.getScroll().x;
        var boxTop = (window.getSize().y / 2) + window.getScroll().y;
        box.style.left = boxLeft + "px";
        box.style.top = boxTop + "px";
        $$('body')[0].appendChild(box);
        var boxMLeft = (box.offsetWidth / 2) * (-1); // box.getSize().x
        box.style.marginLeft = boxMLeft + "px";
        var boxMTop = (box.offsetHeight / 2) * (-1); // box.getSize().y
        box.style.marginTop = boxMTop + "px";

        if (options.url != false) {
            var loading = document.createElement("img");
            loading.src = options.loadIcon;
            loading.className = 'loading';
            mbox.appendChild(loading);
            if ((options.url != false) && (options.url.toLowerCase().indexOf(".png") == -1) && (options.url.toLowerCase().indexOf(".jpg") == -1) && (options.url.toLowerCase().indexOf(".gif") == -1)) {
                var ajax = new Request({
                    url: options.url,
                    onComplete: function () {
                        window.setTimeout(function () {
                            mbox.removeChild(loading);
                            insertMessage();
                        }, options.ajaxDelay);
                    },
                    onSuccess: function (html) {
                        options.message = html;
                    },
                    onFailure: function (html) {
                        options.message = options.ajaxErrorMessage;
                    }
                });
                ajax.send();
            } else {
                var img = document.createElement("img");
                img.src = options.url;
                img.style.visibility = "hidden";
                img.style.position = "absolute";
                img.style.left = "0px";
                img.style.top = "0px";
                mbox.appendChild(img);
                window.setTimeout(function () {
                    faceboxLoadImage(img, loading);
                }, options.ajaxDelay);
            }
        } else {
            insertMessage();
        }
    }

    var faceboxLoadImage = function (img, loading) {
        if ((img.width != null) && (img.width != undefined) && (img.width != "")) {
            options.width = img.width;
            options.height = img.height;
            if ((options.title != "") && (options.title != false))
                var imgAlt = options.title;
            else
                var imgAlt = img.src;
            options.message = '<img src="' + img.src + '" alt="' + imgAlt + '" />';
            mbox.removeChild(img);
            mbox.removeChild(loading);
            insertMessage();
        } else {
            faceboxLoadImage(img, loading);
        }
    }

    var insertMessage = function () {
        var title = false;
        if ((options.title != null) && (options.title != false) && (options.title != "")) {
            title = document.createElement("h2");
            title.innerHTML = options.title;
            title.className = options.classNameTitle;
            mbox.appendChild(title);
        }

        var faceboxMessage = document.createElement("div");
        faceboxMessage.className = "faceboxMessage";
        if (options.height != "auto")
            faceboxMessage.style.height = options.height + "px";
        mbox.appendChild(faceboxMessage);
        faceboxMessage.style.width = options.width + "px";
        if (options.height != "auto")
            faceboxMessage.style.height = options.height + "px";

        var content = options.message;
        faceboxMessage.innerHTML = content;

        if ((options.url != false) && ((options.url.toLowerCase().indexOf(".png") != -1) || (options.url.toLowerCase().indexOf(".jpg") != -1) || (options.url.toLowerCase().indexOf(".gif") != -1)) && ((title == false) || (title == "")) && (options.submitValue == false) && (options.cancelValue == "Cancel") && (options.submitFunction == false)) {
            var img = faceboxMessage.getElementsByTagName("img");
            if (img.length > 0) {
                img[0].style.cursor = "pointer";
                if (window.attachEvent) {
                    img[0].attachEvent("onclick", function () {
                        var fx = new Fx.Morph(box, { duration: 300 });
                        fx.start({ opacity: 0 }).chain(function () { $$('body')[0].removeChild(box); });
                    });
                } else {
                    img[0].addEvent("click", function () {
                        var fx = new Fx.Morph(box, { duration: 300 });
                        fx.start({ opacity: 0 }).chain(function () { $$('body')[0].removeChild(box); });
                    });
                }
            }
        }
        else {
            var faceboxFooter = document.createElement("div");
            faceboxFooter.className = "faceboxFooter";
            mbox.appendChild(faceboxFooter);

            ///add info link
            if ((options.footerLink != false) && (options.footerLink != null) && (options.footerLink != "")) {
                var footerLinkButton = document.createElement("span");
                footerLinkButton.innerHTML = options.footerLinkText;
                footerLinkButton.className = 'faceboxFooterLeftLink';

                faceboxFooter.appendChild(footerLinkButton);
            }

            ///add submit button
            if ((options.submitValue != false) && (options.submitValue != null) && (options.submitValue != "")) {
                var submitButton = document.createElement("input");
                submitButton.setAttribute("type", "button");
                submitButton.className = 'faceboxSubmit';
                submitButton.setAttribute("value", options.submitValue);
                if (window.attachEvent)
                    submitButton.attachEvent("onclick", options.submitFunction);
                else
                    submitButton.addEvent("click", options.submitFunction);
                faceboxFooter.appendChild(submitButton);
                if (options.submitFocus == true)
                    submitButton.focus();
            }

            ///add cancel button
            var cancelButton = document.createElement("input");
            cancelButton.setAttribute("type", "button");
            cancelButton.setAttribute("value", options.cancelValue);
            if (options.cancelFunction == false) {
                if (window.attachEvent) {
                    cancelButton.attachEvent("onclick", function () {
                        instance.close();
                    });
                } else {
                    cancelButton.addEvent("click", function () {
                        instance.close();
                    });
                }
            } else {
                if (window.attachEvent)
                    cancelButton.attachEvent("onclick", options.cancelFunction);
                else
                    cancelButton.addEvent("click", options.cancelFunction);
            }
            faceboxFooter.appendChild(cancelButton);
        }

        if ((options.draggable == true) && (title != false))
            var dragging = new Drag.Move(box, { handle: title });

        var boxMTop = (box.getSize().y / 2) * (-1);
        box.style.marginTop = boxMTop + "px";
    }

    this.close = function () {
        var fx = new Fx.Morph(box, { duration: 300 });
        fx.start({
            opacity: 0
        }).chain(function () {
            $$('body')[0].removeChild(box);
        });
    }

    this.status = function () {
        return $$('body')[0].hasChild(box);
    }

    this.fastclose = function () {
        $$('body')[0].removeChild(box);
    }

    this.returnMessageBox = function () {
        var messageBox = box.getElements(".faceboxMessage")[0];
        return messageBox;
    }

    this.fade = function () {
        var overlayW = mbox.offsetWidth; // mbox.getSize().x
        var overlayH = mbox.offsetHeight; // mbox.getSize().y
        var overlay = document.createElement("div");
        overlay.style.width = overlayW + "px";
        overlay.style.height = overlayH + "px";
        overlay.style.position = "absolute";
        overlay.style.left = "-1px";
        overlay.style.top = "-1px";
        overlay.className = 'faceboxOverlay';
        overlay.style.backgroundColor = "#fff";
        var hide = new Fx.Morph(overlay, { duration: 400 });
        hide.set({
            opacity: options.fadeOpacity
        });
        mbox.appendChild(overlay);
    }

    this.unfade = function () {
        mbox.setAttribute("id", "tmpMBoxId");
        var overlay = $$('#tmpMBoxId .faceboxOverlay'); // mbox.getElements('.faceboxOverlay');
        mbox.setAttribute("id", "");
        if (overlay.length > 0)
            mbox.removeChild(overlay[0]);
        var fx = new Fx.Morph(box);
        fx.set({ opacity: 1 });
    }
}

/// #Header actions

// make these variables global, so that we know if the relevant Faceboxes are open or not
var newLabelBox;
var editLabelBox;
/// Attach events
/// #
if ($('header_new_label')) {
    $('header_new_label').addEvents({
        'click': function () {
            NewLabelWindow('',-1);
            return false;
        }
    });
}
/// New/Edit label
var togglePrivacy = {
    everyone: function () {

        $('privacyicon_111').set('title', 'Everyone');

        $('privacyicon_111').removeClass('lblPr_2');
        $('privacyicon_111').removeClass('lblPr_3');
        $('privacyicon_111').addClass('lblPr_4');

        $('LabelPrivacyValue').set('html', 'Everyone');
    },
    followers: function () {
        $('privacyicon_111').set('title', 'Followers');
        $('privacyicon_111').removeClass('lblPr_2');
        $('privacyicon_111').addClass('lblPr_3');
        $('privacyicon_111').removeClass('lblPr_4');

        $('LabelPrivacyValue').set('html', 'Followers');
    },
    onlyme: function () {
        $('privacyicon_111').set('title', 'Only me');
        $('privacyicon_111').addClass('lblPr_2');
        $('privacyicon_111').removeClass('lblPr_3');
        $('privacyicon_111').removeClass('lblPr_4');

        $('LabelPrivacyValue').set('html', 'Onlyme');
    }
}

var jsHelperLaber = {
    previewText: function () {
        clearTimeout(PreviewTimeout);
        PreviewTimeout = setTimeout(function () {
            if ($('newLabel').get('value').trim().length == 0)
                $('labelPreview').set('html', '&nbsp;&nbsp;');
            else
                $('labelPreview').set('html', $('newLabel').get('value'));
        }, 250);
    },
    overBack: function (bColor, elElementID) {
        $('labelPreview').setStyles({
            'background': bColor
        });
        //jsHelperLaber.setBack(bColor);
    },
    outBack: function () {
        $('labelPreview').setStyles({
            'background': $('labelBackgroundColor').get('value')
        });
    },
    setBack: function (bColor) {
        $('labelBackgroundColor').set('value', bColor);
    },
    overFont: function (bColor, elElementID) {
        $('labelPreview').setStyles({
            'color': bColor
        });
        //jsHelperLaber.setFont(bColor);
    },
    outFont: function () {
        $('labelPreview').setStyles({
            'color': $('labelFontColor').get('value')
        });
    },
    setFont: function (bColor) {
        $('labelFontColor').set('value', bColor);
    }
    ,
    reset: function () {
        var res_fc = $('labelFontColor_reset').get('value');
        var res_bc = $('labelBackgroundColor_reset').get('value');

        jsHelperLaber.overFont(res_fc);
        $('labelFontColor').set('value', res_fc);
        jsHelperLaber.overBack(res_bc);
        $('labelBackgroundColor').set('value', res_bc);
        
    }
}
/// Newlabel window
function NewLabelWindow(elementID,feedID) {
    var newlabelname = '';
    //feedID: apply label in feeds

    if (elementID!='')
        if ($(elementID))//autocomplete create new
            newlabelname=$(elementID).get('html').replace('(create new)', '');

    if (((newLabelBox == null) || !(newLabelBox.status())) && ((editLabelBox == null) || !(editLabelBox.status()))) { // facebox should NOT re-open
        newLabelBox = new Facebox({
            url: '/user/views/createlabel.aspx?labelNAME=' + newlabelname,
            width: 522,
            height: 250,
            cancelValue: 'Cancel',
            submitFunction: function () {
                // get CreateLabel params from Facebox's hidden DIVs
                var labelName = $('newLabel').get('value');
                var privacy = $('LabelPrivacyValue').get('html');
                var isYouTube = $('LabelIsYoutube').get('html');
                var isTwitter = $('LabelIsTwitter').get('html');
                var isDigg = $('LabelIsDigg').get('html');
                var isLastFM = $('LabelIsLastFM').get('html');
                var isMeebo = 'false';
                var labelBackgroundColor = $('labelBackgroundColor').get('value');
                var labelFontColor = $('labelFontColor').get('value');

                CreateLabel(labelName, privacy, isYouTube, isTwitter, isDigg, isLastFM, isMeebo, feedID, labelBackgroundColor, labelFontColor);
                // newLabelBox.close();
            },
            submitValue: 'Create',
            submitFocus: 'Yes'//If true, the submit button will be focused. (Pressing enter will activate it)
        });
        newLabelBox.show();
    }
}
/// Create a label
function CreateLabel(labelName, privacy, isYouTube, isTwitter, isDigg, isLastFM, isMeebo, feedID,labelBackgroundColor, labelFontColor) {
   
    var oCreateLabelAjax = new WADJAX('Labels', { statusBar: false });
    try {
            if ($('ajax_loader'))
                $('ajax_loader').removeClass('dnd');

            oCreateLabelAjax.send('CreateLabel', labelName, privacy, isYouTube, isTwitter, isDigg, isLastFM, isMeebo, labelBackgroundColor, labelFontColor, function (res) {
                if (!res.error) {
                    if ($('ajax_loader'))
                        $('ajax_loader').addClass('dnd');

                    if (res.value == '0')//MARK - user not authenticated
                        Notify.topBarOn('You must be signed in to create a label.', 'red', 6);
                    else if (res.value.indexOf('Error:') == 0)//MARK - error occured; show error message
                        Notify.topBarOn(res.value, 'red', 6);
                    else //MARK - res.value has new label ID
                    {

                        //- Close box
                        if (newLabelBox)
                            newLabelBox.close();
                        //- Top bar with text
                        Notify.topBarOn("Great! The label #" + labelName + " has been created!", "", 6);

                        //- getExternalFeeds
                        var wjxcurate_new = new WADJAX('Profile', { statusBar: false });

                        if (isYouTube)
                            wjxcurate_new.send('GetExternalFeeds', profileInfo.viewerID, 4, function (res) { });
                        if (isTwitter)
                            wjxcurate_new.send('GetExternalFeeds', profileInfo.viewerID, 2, function (res) { });
                        if (isDigg)
                            wjxcurate_new.send('GetExternalFeeds', profileInfo.viewerID, 1, function (res) { });
                        if (isLastFM)
                            wjxcurate_new.send('GetExternalFeeds', profileInfo.viewerID, 3, function (res) { });

                        //- If on owner's profile
                        if (profileInfo.viewerID == profileInfo.ownerID) {
                                    
                            //reload MyData
                            var wjxUser_new = new WADJAX('User', { statusBar: false });
                            wjxUser_new.send('GetLabels', profileInfo.ownerID, 'My', function (res) {
                                try {
                                    if (typeof GetLabelistData.My == 'function') {
                                        GetLabelistData.My();
                                    }
                                    if (typeof setTxtBodyText == 'function') {
                                        setTxtBodyText();
                                    }
                                }
                                catch (Error) {
                                    Notify.alert('Javascript error', 'Javascript error while using [CreateLabel] #' + Error, 'Ok', 'red');
                                }
                            });

                            // 0: from drop downs
                            //>0: from feeds
                            //  : from header

                            if (feedID > 0) {
                                feedActions.apply(feedID, res.value, labelName, '', '', ''); //#apply label on feed
                                //#display new label notification on the left
                                MyElement.reveal('newlabel_wrapper');
                                $('newlabel_container').set('html', '<a id="nwlbl_' + res.value + '"  class="lblDesignColor" href="/' + profileInfo.viewerWadjaID + '#!My/' + res.value + '/1">#' + labelName + '</a>');
                            }
                            else {
                                //stop redirect:(function () { window.location.href = '/' + profileInfo.viewerWadjaID + '#!My/' + res.value + '/1'; }).delay(1 * 1000);
                                //#display new label notification on the left
                                MyElement.reveal('newlabel_wrapper');
                                $('newlabel_container').set('html', '<a id="nwlbl_' + res.value + '"  class="lblDesignColor" href="/' + profileInfo.viewerWadjaID + '#!My/' + res.value + '/1">#' + labelName + '</a>');
                            }
                            //#add color design on link
                            try {
                                $$('.lblDesignColor').each(function (element, index) {
                                    var ttt = element.get('id');
                                    $(ttt).setStyles({
                                        'color': '#' + profileInfo.LinkColor
                                    });
                                });
                            }
                            catch (Error) {

                            }
                        }
                        else //- Load label feeds
                        {
                            //stop redirect:(function () { window.location.href = '/' + profileInfo.viewerWadjaID + '#!My/' + res.value + '/1'; }).delay(1 * 1000);
                            MyElement.reveal('newlabel_wrapper');
                            $('newlabel_container').set('html', '<a id="nwlbl_' + res.value + '" class="lblDesignColor" href="/' + profileInfo.viewerWadjaID + '#!My/' + res.value + '/1">#' + labelName + '</a>');
                            //#add color design on link
                            try {
                                $$('.lblDesignColor').each(function (element, index) {
                                    var ttt = element.get('id');
                                    $(ttt).setStyles({
                                        'color': '#' + profileInfo.LinkColor
                                    });
                                });
                            }
                            catch (Error) {

                            }
                        }
                    }
                }
                else {
                    if ($('ajax_loader'))
                        $('ajax_loader').addClass('dnd');
                    Notify.topBarOn('Error: ' + res.value + '. Please try again later.', 'red', 6);
                }
            });
    }
    catch (Error) {return Error; }
    
}

if ($('HomeLabel')) {
    $('HomeLabel').addEvents({
        'click': function () {
            // only if the signed-in user is the profile owner...
            if (profileInfo.profileBelongsToViewer) {
                EditLabel(wProfile.Current.LabelID.toString());
                    /*if (((editLabelBox == null) || !(editLabelBox.status())) && ((newLabelBox == null) || !(newLabelBox.status()))) { // New/Edit facebox should NOT re-open
                    editLabelBox = new Facebox({
                        url: '/user/views/createlabel.aspx?labelID=' + wProfile.Current.LabelID.toString(),
                        width: 522,
                        height: 250,
                        cancelValue: 'Cancel',
                        submitFunction: function () {
                            // get UpdateLabel params from Facebox's hidden DIVs
                            var labelID = $('LabelIdValue').get('html');
                            // if it's a system label, pass an empty string as label name, to avoid rename error checking
                            var labelName = ($('newLabel').get('disabled') ? '' : $('newLabel').get('value'));
                            // Disable privacy for MESSAGE,TRASH, HELP, POINTS
                            var privacy = $('LabelPrivacyValue').get('html');
                            // Disable privacy for MESSAGE,TRASH, HELP, POINTS, CONTACTS
                            var isYouTube = $('LabelIsYoutube').get('html');
                            var isTwitter = $('LabelIsTwitter').get('html');
                            var isDigg = $('LabelIsDigg').get('html');
                            var isLastFM = $('LabelIsLastFM').get('html');
                            var isMeebo = 'false';
                            var labelBackgroundColor = $('labelBackgroundColor').get('value');
                            var labelFontColor = $('labelFontColor').get('value');

                            UpdateLabel(labelID, labelName, privacy, isYouTube, isTwitter, isDigg, isLastFM, isMeebo, labelBackgroundColor, labelFontColor);
                            editLabelBox.close();

                        },
                        submitValue: 'Edit',
                        submitFocus: 'Yes'//If true, the submit button will be focused. (Pressing enter will activate it)
                    });
                    editLabelBox.show();
                }*/
            }
            return false;
        }
    });
}

//#edit-design label
function EditLabel(labelID, sourcepage) {
    if (((editLabelBox == null) || !(editLabelBox.status())) && ((newLabelBox == null) || !(newLabelBox.status()))) { // New/Edit facebox should NOT re-open
            editLabelBox = new Facebox({
                url: '/user/views/createlabel.aspx?labelID=' + labelID,
                width: 522,
                height: 250,
                cancelValue: 'Cancel',
                submitFunction: function () {
                    // get UpdateLabel params from Facebox's hidden DIVs
                    var labelID = $('LabelIdValue').get('html');
                    // if it's a system label, pass an empty string as label name, to avoid rename error checking
                    var labelName = ($('newLabel').get('disabled') ? '' : $('newLabel').get('value'));
                    // Disable privacy for MESSAGE,TRASH, HELP, POINTS
                    var privacy = $('LabelPrivacyValue').get('html');
                    // Disable privacy for MESSAGE,TRASH, HELP, POINTS, CONTACTS
                    var isYouTube = $('LabelIsYoutube').get('html');
                    var isTwitter = $('LabelIsTwitter').get('html');
                    var isDigg = $('LabelIsDigg').get('html');
                    var isLastFM = $('LabelIsLastFM').get('html');
                    var isMeebo = 'false';
                    var labelBackgroundColor = $('labelBackgroundColor').get('value');
                    var labelFontColor = $('labelFontColor').get('value');

                    UpdateLabel(labelID, labelName, privacy, isYouTube, isTwitter, isDigg, isLastFM, isMeebo, labelBackgroundColor, labelFontColor, sourcepage);
                    editLabelBox.close();

                },
                submitValue: 'Edit',
                submitFocus: 'Yes'//If true, the submit button will be focused. (Pressing enter will activate it)
            });
            editLabelBox.show();
    }
}

/// Update a label
function UpdateLabel(labelID, labelName, privacy, isYouTube, isTwitter, isDigg, isLastFM, isMeebo, labelBackgroundColor, labelFontColor, sourcepage) {
   var oEditLabelAjax = new WADJAX('Labels', { statusBar: false });
    try {
        Notify.spinnerOn('Loading...', 'Still loading', 5);
        oEditLabelAjax.send('UpdateLabel', labelID, labelName, privacy, isYouTube, isTwitter, isDigg, isLastFM, isMeebo, labelBackgroundColor, labelFontColor, function (res) {
            if (!res.error) {
                Notify.spinnerOff('done', 1);
                if (res.value == '0')
                // user not authenticated
                    ;
                else if (res.value.indexOf('Error:') == 0)
                // error occured; show error message
                    Notify.topBarOn(res.value.substr(('Error:').length), '', 6);
                else {
                    if (sourcepage == 0) {
                        //#from manage labels
                        //#update privacy icon
                    }
                    else {
                        //#from profile
                        //#update privacy icon
                        LabelPrivacyIcon(privacy.replace("Onlyme", "2").replace("Followers", "3").replace("Everyone", "4"));
                        //#refresh label-feeds
                        wProfile.Load(wProfile.Current.DetailsID, "My", labelID, 1, true);
                    }
                }
            }
            else {
                Notify.spinnerOff('done', 1);
                Notify.topBarOn('There was an error', '', 6);
            }
        });
    }
    catch (Error) { alert(Error); }
}

/// Left bar-functions
if ($('left_container_bio_more')) {
    $('left_container_bio_more').addEvents({
        'click': function () {
            if ($('left_container_bio_more').get('class').indexOf('arrowOff') >= 0) {
                $('left_container_bio_more').removeClass('arrowOff');
                $('left_container_bio_more').addClass('arrowOn');
            }
            else {
                $('left_container_bio_more').removeClass('arrowOn');
                $('left_container_bio_more').addClass('arrowOff');
            }
            MyElement.toggleReveal('MoreBIO');

        }
    });
}

if ($('left_container_labels_more')) {
    $('left_container_labels_more').addEvents({
        'click': function () {

            if ($('more_new_counter').get('class').indexOf('arrowOff_trans') >= 0) {
                $('more_new_counter').removeClass('arrowOff_trans');
                $('more_new_counter').addClass('arrowOn_trans');
            }
            else {
                $('more_new_counter').removeClass('arrowOn_trans');
                $('more_new_counter').addClass('arrowOff_trans');
            }
            //#Retrieve user's labels
            MyElement.toggleReveal('MoreLabels');
            var wjxMyLabels = new WADJAX('labels', { statusBar: false });
            if ($('MoreLabels').get('html').trim() == '&nbsp;') {
                $('MoreLabels').addClass('loadingTop');

                wjxMyLabels.send('GetUserLabels', profileInfo.ownerID, profileInfo.viewerID, profileInfo.ownerWadjaID, function (r) {
                    if (r.error != null) return;
                    else {
                        if (r.value.trim() != '') {
                            $('MoreLabels').set('html', r.value);
                            $('MoreLabels').removeClass('loadingTop');
                        }
                        try {
                            $$('.lblDesignColor').each(function (element, index) {
                                var ttt = element.get('id');
                                $(ttt).setStyles({
                                    'color': '#' + profileInfo.LinkColor
                                });
                            });
                        }
                        catch (Error) {

                        }
                    }
                });
            }

        }
    });
}
//#More left label links
function more_labels_link(myhref) {
    if ($('MoreLabels'))
        MyElement.dissolve('MoreLabels');
    window.location.href = myhref;
}

/// #Cart functions
function OpenCart() {
    var SMSbox = new Facebox({
        url: '/cart/iframe.aspx',
        width: 775,
        height: 500,
        //message: '<div class=\"pad10 tac\">This service is under maintenance. Please try again later.</div>',
        title: 'Cart',
        cancelValue: 'Close',
        cancelFunction: function () {
            if (document.getElementById('frame_file').contentWindow.WhenClose() == "1")
                document.getElementById('frame_file').src = '/cart/gwallet/gwform.aspx';
            else
                SMSbox.close();
        }
    });
    SMSbox.show();
}

var Cartbox = null;
function OpenNewCart() {
    Cartbox = new Facebox({
        url: '/cart/new/iframe.aspx',
        width: 650,
        height: 370,
        //message: '<div class=\"pad10 tac\">This service is under maintenance. Please try again later.</div>',
        title: 'Purchase points <span class=\"f_r creditsSpCart\">' + profileInfo.points + ' points</span>',
        footerLink: true, // adds a link before submit buttons
        footerLinkHref: '',
        footerLinkText: '<div id=\'cartFooterStart\'>Note that by buying Wadja Points you accept the <span class=\"lnk\" onclick=\"window.open(\'/terms_sale.aspx\')\">Terms of Sale</span>.</div><div id=\'cartFooter\' class=\'dnd lnk\' onclick=\'CartBack();\'>&larr; Change payment method</div>',
        cancelValue: 'Close',
        cancelFunction: function () {
            Cartbox.close();
        },
        submitValue: 'Continue',
        submitFunction: function () {
            $('cartFooter').removeClass('dnd');
            $('cartFooterStart').addClass('dnd');
            document.getElementById('frame_file').contentWindow.Continue();
        }
    });
    Cartbox.show();

}

function CartBack() {
    try {
        document.getElementById("frame_file").contentWindow.Back();
        $('cartFooter').addClass('dnd');
        $('cartFooterStart').removeClass('dnd');
    }
    catch (Error) {
        //document.getElementById("frame_file").src = '/cart/new/iframe.aspx';
        Cartbox.close();
        OpenNewCart();
    }
}

function HideLeftBio() {
    Notify.spinnerOn('Loading...', 'Still loading', 5);
    var oWadjaX = new WADJAX('user', { statusBar: false });
    oWadjaX.send('HideBioEarnCredits', profileInfo.ownerID, function (res) {
        if (!res.error) {
            Notify.spinnerOff('done', 1);
            $('profileStatTbl').addClass('dnd');
            $('yellowLeft').removeClass('yellowLeft');
        }
    });
}
function $i(aID) {
    var rv = null;
    var frame = (document.getElementById ? $(aID) : document.all[aID]);
    // if contentDocument exists, W3C compliant (e.g. Mozilla)
   
    if (frame.contentDocument)
        rv = frame.contentDocument;
    else
        rv = document.frames[aID].document; // bad IE  ;)
    
    return rv;
}

function UpdateCreditsDisplay() {
    if ($("topPoints") != null) {
        var Points_Ajax = new WADJAX('User', {});
        Points_Ajax.send('UpdateCreditsDisplay', function (res) {
            if (!res.error) {
                if (res.value.length > 0)
                    $("topPoints").set("html", res.value + "&nbsp;Points");
            }
        });
    }
}


// This replaces all instances of 'from' to 'to' even when
// 'from' and 'to' are similar (i.e .replaceAll('a', 'a '))
String.prototype.replaceAll = function (search, replace) {
    if (replace === undefined) {
        return this.toString();
    }
    return this.split(search).join(replace);
}

String.prototype.Contains = function (objElm) {
    return (this.indexOf(objElm) > -1);
};

String.prototype.urlEncode = function () {
    return encodeURIComponent(this);
};

String.prototype.urlDecode = function () {
    return decodeURIComponent(this.replace(/\+/g, " "));
};

///WADJAX JS
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
* Desc:    WADJA AJAX Class                                               *
* Author:  Theofanis Pantelides (theo@wadja.com)                          *
* Date:    November 6, 2009                                               *
* Usage:   var varName = new WadjaSuggest('textBoxName', { });            *
*          varName.send('func', 'param1' [, 'param2' [..]], func(r) { }); *
\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

var WADJAX = new Class({

    Implements: [Options],

    /************* WADJAX Options *************/
    options: {
        isJSON: false,      /* String is JSON object */
        method: 'post',     /* Type of request */
        statusBar: true     /* Show Yellow loading bar */
    },

    callback: false,

    response: { request: {}, error: null, value: null, context: null },

    /************* Initialize Class *************/
    initialize: function (type, options) {
        this.setOptions(options);
        this.URL = '/controllers/wAjax.' + type + '.ashx';

    },

    send: function () {
        var oQ = "m=" + arguments[0];
        var o_Val = null;
        var o_Err = null;

        for (var i = 0; i < arguments.length; i++) {
            if (typeof (arguments[i]) === "function") {
                this.callback = arguments[i];
            } else {
                oQ += ("&q" + i + "=" + encodeURIComponent(arguments[i]));
            }
        }

        var statBar = this.options.statusBar;

        var notAsync = (this.callback == false);

        var ajxReq = new Request({

            url: this.URL,
            method: this.options.method,
            noCache: true,
            wadjax: this,
            async: (!notAsync),
            debug: (this.URL + '?' + oQ),

            onRequest: function () {
                //$('wzilla').removeClass('dnd');
                //$('wzilla').set('html', $('wzilla').get('html') + this.options.debug + " | ");
                if (statBar) { // Show Yellow Bar
                    Notify.spinnerOn("Loading...", "Still loading...", 5)
                }
            },
            onSuccess: function (oResp) {
                o_Val = oResp;

                if (this.options.wadjax.callback) {
                    this.options.wadjax.response.value = o_Val;
                    this.options.wadjax.callback(this.options.wadjax.response);
                }
                if (statBar) { // Show Yellow Bar
                    Notify.spinnerOff("Done!", 1)
                }
            },
            onCancel: function () {
                if (statBar) { // Show Yellow Bar
                    Notify.spinnerOff("Cancelled!", 3)
                }
            },
            onFailure: function (xhr) {
                try {
                    o_Err = this.options.wadjax.response.error = (xhr.status + "-" + xhr.statusText);
                } catch (exxdfs) {
                    //o_Err = this.options.wadjax.response.error = ("STATUS: " + xhr.status);
                    o_Err = this.options.wadjax.response.error = ("Something went wrong. Please refresh page and try again.");
                }
                if (this.options.wadjax.callback) {
                    this.options.wadjax.callback(this.options.wadjax.response);
                }
                if (statBar) { // Show Yellow Bar
                    Notify.spinnerOff("An error occurred!", 2);
                }
            }
        });

        //alert(this.options.debug);
        ajxReq.send(oQ);

        if (notAsync) {
            return { value: o_Val, error: o_Err };
        }
    }
});

function getElement(aID) {
    return (document.getElementById) ? $(aID) : document.all[aID];
}
function getIFrameDocument(aID) {
    var rv = null;
    var frame = getElement(aID);
    // if contentDocument exists, W3C compliant (e.g. Mozilla)

    if (frame.contentDocument)
        rv = frame.contentDocument;
    else
        rv = document.frames[aID].document; // bad IE  ;)

    return rv;
}

//#Get URL Parameters (QueryStrings) using Javascript
function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}
//#Bootstrap

var bootloader = {
    load: function (url, callback) {
        var script = document.createElement("script")
        script.type = "text/javascript";

        if (script.readyState) {  //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" ||
                    script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else {  //Others
            script.onload = function () {
                callback();
            };
        }

        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }
}