﻿/// <reference path="MooTools.js" />

Element.implement({
    show: function () {
        this.setStyle('display', 'block');
    },
    hide: function () {
        this.setStyle('display', 'none');
    },
    isVisible: function () {
        return !(this.getStyle('display') == 'none');
    },
    toggle: function () {
        return this[this.isVisible() ? 'hide' : 'show']();
    },
    collapsibleBox: function () {
        return this.retrieve('box');
    },
    swapClass: function (remove, add) {
        return this.removeClass(remove).addClass(add);
    },
    ShowSmallLoad: function () {
        this.set('html', '<img class="Middle" style="padding:0px 5px 0 0;" src=\'/Images/Global/load2.gif\' />');
    },
    fadeOutSlideOut: function (onComplete) {
        this.set('tween', { onComplete: function () {
            this.set('slide', { onComplete: function () { if (onComplete) onComplete(); } });
            this.slide('out');
        } .bind(this)
        });
        this.fade('out');
    },
    slideInFadeIn: function (onComplete) {
        this.fade('hide');
        this.slide('hide');
        this.set('slide', { onComplete: function () {
            this.set('tween', { onComplete: function () { if (onComplete) onComplete(); } });
            this.fade('in');
        } .bind(this)
        });
        this.slide('in');
    }

});

window.addEvent('domready', function () {
    MakeMiniProfiles();
    SetupHelp();
    $$('.beta').addEvent('click', function (event) {
        event.preventDefault();
        LoadLightBoxWithXHR(450, '/controls/ajax/beta.htm');
    });
});

function SetupHelp() {
    $$('.HelpIcon').each(function (item) {
        if (item.get('title') && item.get('title') != "") {
            item.store('HelpText', item.get('title'));
            item.set('title', '');
        }
    });
    $$('.HelpIcon').removeEvent('click', ShowHelp).addEvent('click', ShowHelp);
    $('KLASHelp').removeEvents('click').addEvent('click', function (e) {
        e.stopPropagation();
    });
}

function ShowHelp(e) {
    if (!$('KLASHelp').isVisible() || $('HelpText').get('html') != this.retrieve('HelpText')) {
        $('HelpText').set('html', this.retrieve('HelpText'));
        $('KLASHelp').show();
        $('KLASHelp').position({ 'relativeTo': this.getParent(), 'position': 'bottomLeft', 'offset': { x: 0, y: -1} });
        var hideHelp = function () { $('KLASHelp').hide(); $$('body').removeEvent('click', hideHelp); };
        $$('body').addEvent('click', hideHelp);
        e.stop();
    }
}

function CheckAll(CSS_Selector, checked) {
    $$(CSS_Selector).set('checked', checked);
}

function bookmarkCurrentPage() {
    LoadLightBoxWithXHR(500, '/Controls/Ajax/BookmarkCurrentPage.aspx', 'bookmarkSetUp()');
}

function bookmarkSetUp() {
    $('txtPageBookmark').set('value', document.title.replace(' - KLAS Helps Healthcare Providers by Measuring Vendor Performance', ''));
    $('hdnPageBookmark').set('value', window.location);
}

function savePageBookmark() {
    new Request.HTML({
        url: '/Controls/Ajax/SaveBookmark.ashx',
        method: 'post',
        noCache: true,
        link: 'chain',
        data: $('PageBookmarkForm').toQueryString(),
        onSuccess: function () {
            HideLightBox();
            if ($('bookmarkList')) {
                $('bookmarkList').set('load', { noCache: true });
                $('bookmarkList').load('/myKLAS/Ajax/ListBookmarks.ashx');
            }
        }
    }).send();
}

function Authenticate(element, link) {

    var valid = true;
    var usernameEl = $$('#' + element + ' input[type=text]')[0];
    if (usernameEl.get('value').trim().length == 0) {
        usernameEl.getNext('.formError').show();

        var keydownEvent;
        keydownEvent = function () {
            usernameEl.getNext('.formError').hide();
            usernameEl.removeEvent('keydown', keydownEvent);
        }
        usernameEl.addEvent('keydown', keydownEvent);
        valid = false;
    }

    var passwordEl = $$('#' + element + ' input[type=password]')[0];
    if (passwordEl.get('value').trim().length == 0) {
        passwordEl.getNext('.formError').show();

        var keydownEvent2;
        keydownEvent2 = function () {
            passwordEl.getNext('.formError').hide();
            passwordEl.removeEvent('keydown', keydownEvent2);
        }
        passwordEl.addEvent('keydown', keydownEvent2);
        valid = false;
    }

    if (!valid)
        return false;

    $(link).set('html', $(link).get('html') + "<img src='/Images/Global/loadgreen.gif' style='padding:2px 0 0 5px;' />");
    new Request.JSON({
    	url: '/Controls/Ajax/Authenticate.ashx',
    	method: 'post',
    	noCache: true,
    	link: 'chain',
    	data: {
    		user: $$('#' + element + ' input[type=text]')[0].get('value'),
    		pass: $$('#' + element + ' input[type=password]')[0].get('value')
    	},
    	onSuccess: function (jsonObj) {
    		if (jsonObj.userCorrect) {
    			if (jsonObj.Master) {
    				if (jsonObj.Vendor) {
    					window.location = '/SignUp/SetupSecondaryVendor.aspx?m=' + jsonObj.AccessID;
    				}
    				else
    					window.location = '/SignUp/SetupSecondary.aspx?m=' + jsonObj.AccessID;
    			}
    			else
    				eval(link.href);
    		}
    		else {
    			if ($$('#' + element + " .loginError").length > 0)
    				$$('#' + element + " .loginError")[0].show();
    			if (jsonObj.message == 'Invalid Email')
    				$('divInvalidEmail').show();
    			else
    				$('LoginError').show();
    			$(link).set('html', 'Login');
    		}
    	}
    }).send();
    return false;
}

function TableHovers(ClassName) {
    $$('.' + ClassName).each(function (item, index) {
        item.store('back', item.getStyle('background-color'));
        item.addEvents({
            'mouseover': function () {
                item.setStyle('background-color', '#cccccc');
            },
            'mouseout': function () {
                if (index % 2 == 1)
                    item.setStyle('background-color', item.retrieve('back'));
                else
                    item.setStyle('background-color', item.retrieve('back'));
            }
        });
    });
}

function ToggleTabs(ulID, AjaxUrl, UpdateDiv, LoadingID, index, OnCompleteScript) {
    ChangeSelectedTab('#' + ulID + ' li', index);

    $(UpdateDiv).show();
    $(UpdateDiv + '_TabContent').hide();

    LoadTabPage(AjaxUrl, UpdateDiv, LoadingID, OnCompleteScript, ulID, index);
}

function ToggleTabsNoXHR(ulID, UpdateDiv, index, OnCompleteScript) {
    ChangeSelectedTab('#' + ulID + ' li', index);

    $(UpdateDiv).hide();
    $(UpdateDiv + '_TabContent').show();

    $(UpdateDiv + '_TabContent').getChildren().each(function (item, index2) {
        if (item.get('id') == (UpdateDiv + '_' + index))
            item.show();
        else
            item.hide();
    });

    eval(OnCompleteScript);
}

function ChangeSelectedTab(selector, index) {
    $$(selector).each(function (item, index2) {
        if (index == index2)
            item.addClass('Selected');
        else
            item.removeClass('Selected');
    });
}

function LoadTabPage(AjaxUrl, UpdateDiv, LoadingID, OnCompleteScript, ulID, index) {

    if (!AjaxUrl.contains('PlaceHolder.ashx')) {

        var newAjaxUrl = $$('#' + ulID + ' li')[index].retrieve('ajaxurl');
        if (!newAjaxUrl)
            newAjaxUrl = '';

        new Request.HTML({
            noCache: true,
            onRequest: function () {
                $(LoadingID).addClass('Loading');
            },
            onComplete: function (responseTree, responseElements, responseHTML, responseJavaScript) {
                $(UpdateDiv).set('html', responseHTML);
                $(LoadingID).removeClass('Loading');
                eval(OnCompleteScript);
            }
        }).get(AjaxUrl + newAjaxUrl);
    }
    else {
        eval(OnCompleteScript);
    }
}

function LoadLightBoxWithXHR(innerWidth, url, OnCompleteScript, fitInWindow) {
    $('LightBoxContent').set('html', '<div style=\' height:100px; background:url(/Images/Global/LoadLarge.gif) no-repeat 50% 50%;\' ></div>')
    new Request.HTML({
        url: url,
        noCache: true,
        method: 'get',
        update: $('LightBoxContent'),
        onSuccess: function (tree, elements, responseHTML) {
            var inputs = $('LightBoxContent').getElements('input[type=text],textarea');
            if (inputs.length > 0)
                inputs[0].focus();

            eval(OnCompleteScript);
            if (fitInWindow || fitInWindow === undefined) {
                var maxHeight = window.getSize().y - 150;
                if ($('LightBoxContent').getSize().y > maxHeight) {
                    $('LightBoxContent').setStyles({
                        height: maxHeight + 'px',
                        overflow: 'auto'
                    });
                    $('LightBoxContent').scrollTop = 0;
                }
            }
            var scroll = window.getScrollSize();
            $('LightBox').setStyles({
                width: scroll.x,
                height: scroll.y
            });
        }
    }).send();

    LoadLightBox(innerWidth, $('LightBoxWrapper'));
}

function LoadLightBox(innerWidth, element) {
    var scroll = window.getScrollSize();
    var scroll2 = window.getScroll();

    $('LightBox').setStyles({
        opacity: .7,
        background: '#000000',
        width: scroll.x,
        height: scroll.y,
        position: 'absolute',
        top: 0,
        left: 0,
        display: 'block',
        zIndex: 10
    });

    $('LightBox').store('popper', element);

    $(element).setStyles({
        top: scroll2.y + 50,
        width: innerWidth,
        left: (scroll.x - innerWidth) / 2,
        display: 'block',
        zIndex: 11,
        position: 'absolute'
    });

    var inputs = $(element).getElements('input[type=text],textarea');
    if (inputs.length > 0)
        inputs[0].focus();
}

function HideLightBox() {
    $('LightBox').setStyle('display', 'none');
    $($('LightBox').retrieve('popper')).setStyle('display', 'none');
    $('LightBoxContent').setStyle('height', '');
}

var miniProfileTimer;

function MakeMiniProfiles() {
    if ($$('.ProfilePhoto').length > 0) {
        if (!$('MiniProfileDiv')) {
            var profile = new Element('div', {
                'styles': { 'display': 'none' },
                'class': 'MiniProfile',
                'id': 'MiniProfileDiv'
            });
            var triangle = new Element('div', { 'class': 'MiniProfileTriangle' });
            var box = new Element('div', { 'class': 'MiniProfileBox' });
            profile.inject(document.body, 'bottom');
            triangle.inject(profile, 'top');
            box.inject(profile, 'bottom');
        }
        $$('.ProfilePhoto').each(function (item) {
            if (item.get('title')) {
                item.store('klasid', item.get('title'));
                item.set('title', '');
                item.addEvents({
                    'mouseenter': function () {
                        miniProfileTimer = (function () {
                            var profile = $('MiniProfileDiv');
                            var box = profile.getChildren('.MiniProfileBox')[0];
                            if (profile.retrieve(this.retrieve('klasid').toString()) == null) {
                                new Request.HTML({
                                    url: '/Profile/Ajax/MiniProfile.ashx',
                                    method: 'post',
                                    noCache: false,
                                    data: { k: this.retrieve('klasid') },
                                    update: box,
                                    onComplete: function (responseTree, responseElements, responseHTML, responseJavaScript) {
                                        profile.store(this.retrieve('klasid').toString(), box.get('html'));
                                        showMiniProfile(profile, item);
                                    } .bind(this)
                                }).send();
                            }
                            else {
                                box.set('html', profile.retrieve(this.retrieve('klasid').toString()));
                                showMiniProfile(profile, item);
                            }
                        }).bind(this).delay(500);
                    } .bind(item),
                    'mouseout': function () {
                        $clear(miniProfileTimer);
                        if ($('MiniProfileDiv').isVisible()) {
                            $('MiniProfileDiv').hide();
                            $('MiniProfileDiv').setStyle('padding-top', '');
                            $$('#MiniProfileDiv .MiniProfileTriangle').setStyle('margin-top', '');
                        }
                    } .bind(item)
                });
            }
        });
    }
}

function showMiniProfile(profile, item) {
    $('MiniProfileDiv').show();
    var kids = profile.getChildren();
    if ((item.getCoordinates().right + kids[0].getSize().x + kids[1].getSize().x + 10) < window.getSize().x.toInt()) {
        profile.position({ 'relativeTo': item, 'position': 'top-right', 'offset': { x: -3, y: -15} });
        profile.removeClass('right');
    }
    else {
        profile.position({ 'relativeTo': item, 'position': 'upperleft', 'offset': { x: 3, y: -15 }, edge: 'upperright' });
        profile.addClass('right');
    }
    if (profile.getSize().y < 35) {
        profile.setStyle('padding-top', 12);
        profile.getChildren('.MiniProfileTriangle').setStyle('margin-top', 8);
    }
}

function LoadQuickCompare() {
    $('QCBox').scrollTop = 0;
    $$('.sel_Prod').each(function (item) {
        item.addEvent('click', function () {
            item.toggleClass('sel_Selected');
            storeQuickCompareData();
        });
    });
}


function storeQuickCompareData() {
    var ids = '';
    $$('.sel_Selected').each(function (item) {
        ids += '[' + item.get('id') + ']';
    });
    $$('.Tabs li').each(function (item) {
        item.store('ajaxurl', '&ids=' + ids);
    });
}