/**
 * SourceBits Technologies Pvt. Ltd.
 * #63, 19th Main
 * Rajajinagar 2nd Block
 * Bangalore, KA, India
 * www.sourcebits.com
 *
 * @author  ramses
 * @since   Sep 23, 2008 5:11:35 PM
 * @version $Id: application.js 2279 2009-07-04 11:52:27Z ramses $
 */

$(document).ready(
    function() {
        (function() {
            var search = $('#search');

            if (search.length == 1) {
                var searchValue = search.val();

                var empty = function() {
                    if (searchValue == search.val()) {
                        search.val('');
                    }
                }

                var restore = function() {
                    if (search.val() == '') {
                        search.val(searchValue);
                    }
                }

                search.focus(function() {
                    empty();
                });

                search.blur(function() {
                    restore();
                });
                
                search.keyup(function(e) {
                    if (!e) {
                        e  = window.event;
                    }
                    
                    if (27 == e.keyCode) {
                        empty();
                    }
                });
            }
        })();

        var PoliceAgenda = jinj.Class();
            PoliceAgenda.prototype = {
                baseUrl: window.location.protocol + '//' + window.location.hostname + '/',
                userClient: new UserClient(),

                capitalize: function(string)
                {
                    return string.substring(0, 1).toUpperCase()
                         + string.substring(1).toLowerCase();
                },

                getBody: function(win)
                {
                    var document = win.document, body;
        
                    if (document.body) {
                        body = document.body;
                    } else {
                        body = document.getElementsByTagName('body')[0];
                    }

                    if (typeof(body) == 'undefined') {
                        throw new Error('Tag BODY is not present in this document.');
                    }

                    return body;
                },

                getDocumentElement: function(win)
                {
                    var document = win.document, html;

                    if (document.documentElement) {
                        html = document.documentElement;
                    } else {
                        html = document.getElementsByTagName('html')[0];
                    }

                    if (typeof(html) == 'undefined') {
                        throw new Error('Tag HTML is not present in this document.');
                    }

                    return html;
                },

                getWindowDimension: function(property, includeScrollSize, win)
                {
                    if (typeof(property) == 'undefined') {
                        throw new Error('Define which size property (width or height) you want to retrieve.');
                    } else {
                        property = this.capitalize(property);
        
                        if ('Height' != property && 'Width' != property) {
                            throw new Error('Invalid property set. Valid options are width or height.');
                        }
                    }

                    if (typeof(includeScrollSize) == 'undefined') {
                        includeScrollSize = true;
                    }

                    if (typeof(win) == 'undefined') {
                        win = window;
                    }

                    var dimension = 0,
                        orientation = (property == 'Width') ? 'X' : 'Y',
                        html = this.getDocumentElement(win),
                        body = this.getBody(win);
        
                    var windowScrollSize = 0,
                        windowClientSize = 0;
        
                    var htmlScrollSize = 0,
                        htmlClientSize = 0,
                        htmlOffsetSize = 0;
        
                    var bodyMaxScroll  = 0,
                        bodyClientSize = 0,
                        bodyOffsetSize = 0;
        
                    if (typeof(win['inner' + property]) != 'undefined') {
                        windowClientSize = win['inner' + property];
                    }
        
                    if (typeof(html['client' + property]) != 'undefined') {
                        htmlClientSize = html['client' + property];
                    }
        
                    dimension = Math.max(windowClientSize, htmlClientSize);
        
                    if (includeScrollSize) {
                        if (typeof(win['scrollMax' + orientation]) != 'undefined') {
                            windowScrollSize = dimension + win['scrollMax' + orientation];
                        }
        
                        if (typeof(html['offset' + property]) != 'undefined') {
                            htmlOffsetSize = html['offset' + property];
                        }
        
                        if (typeof(html['scroll' + property]) != 'undefined') {
                            htmlScrollSize = html['scroll' + property];
                        }
        
                        if (typeof(body['client' + property]) != 'undefined') {
                            bodyClientSize = body['client' + property];
                        }
        
                        if (typeof(body['offset' + property]) != 'undefined') {
                            bodyOffsetSize = body['offset' + property];
                        }
        
                        dimension = Math.max(
                            windowScrollSize,
                            htmlOffsetSize,
                            htmlScrollSize,
                            bodyClientSize,
                            bodyOffsetSize
                        );
                    }
        
                    return dimension;
                },
        
                getScrollPosition: function(orientation, win)
                {
                    if (typeof(orientation) == 'undefined') {
                        throw new Error('orientation can not be null.');
                    } else {
                        orientation = this.capitalize(orientation);
        
                        if ('Top' != orientation && 'Left' != orientation) {
                            throw new Error('Invalid orientation. Valid options are top or left.');
                        }
                    }
        
                    if (typeof(win) == 'undefined') {
                        win = window;
                    }
        
                    var html = this.getDocumentElement(win);
                    var windowScrollPosition = 0, htmlScrollPosition = 0;
                    var o = (orientation == 'Left') ? 'X' : 'Y';
        
                    if (typeof(win['scroll' + o]) != 'undefined') {
                        windowScrollPosition = win['scroll' + o];
                    }
        
                    if (typeof(html['scroll' + orientation]) != 'undefined') {
                        htmlScrollPosition = html['scroll' + orientation];
                    }
        
                    return Math.max(windowScrollPosition, htmlScrollPosition);
                },
        
                centerElement: function(element, onPage, fixScrollPosition, anchors)
                {
                    if (typeof(onPage) == 'undefined') {
                        onPage = true;
                    }
        
                    if (typeof(fixScrollPosition) == 'undefined') {
                        fixScrollPosition = true;
                    }
        
                    if (typeof(anchors) == 'undefined') {
                        anchors = {top: 0, left: 0};
                    } else {
                        if (typeof(anchors) != 'object') {
                            throw new Error('Invalid type for anchors.');
                        }
        
                        if (typeof(anchors.top) == 'undefined') {
                            anchors.top = 0;
                        }
        
                        if (typeof(anchors.left) == 'undefined') {
                            anchors.left = 0;
                        }
                    }
        
                    var screenHeight = (this.getWindowDimension('height', onPage) - element.offsetHeight) / 2;
                    var screenWidth  = (this.getWindowDimension('width', onPage) - element.offsetWidth) / 2;
        
                    if (fixScrollPosition) {
                        screenHeight += this.getScrollPosition('top');
                        screenWidth  += this.getScrollPosition('left');
                    }
        
                    var top = screenHeight + anchors.top;
                    var left = screenWidth + anchors.left;
        
                    $(element).css('position', 'absolute');
                    $(element).css('top', top + 'px');
                    $(element).css('left', left + 'px');
                    
                    return this;
                },
        
                feedbackFadeout: function()
                {
                    if ($('#feedback').length > 0) {
                        setTimeout("$('#feedback').slideUp()", 30000);
                    }
                },
        
                errorsFadeout: function()
                {
                    if ($('.errors').length > 0) {
                        setTimeout("$('.errors').fadeOut('slow')", 30000);
                    }
                },
        
                setFeedback: function(message, level)
                {
                    if (!message) {
                        throw new Error('A feedback message must be provided.');
                    }
        
                    if (!level) {
                        level = 'info';
                    }
        
                    var content = document.createElement('div');
                        content.className = 'feedback ' + level;
                        content.innerHTML = message;
        
                    if ($('#feedback').length < 1) {
                        var feedback = document.createElement('div');
                            feedback.id = 'feedback';
                        $('#content').prepend(feedback);
                    } else {
                        $('#feedback').empty()
                        $('#feedback').show();
                    }
        
                    $('#feedback').append(content);
                    this.feedbackFadeout();
                },
        
                toggleLoader: function()
                {
                    if ($('#loader').length < 1) {
                        var loader = document.createElement('div');
                            loader.id = 'loader';
                            loader.style.display = 'none';
        
                        $('body').append(loader);
                    }
        
                    $('#loader').toggle();
                },
        
                lockScreen: function()
                {
                    if ($('#locker').length < 1) {
                        var body = this.getBody(window);
                        var locker = document.createElement('div');
                            locker.id = 'locker';
        
                        $(locker).css('display', 'block');
                        $(locker).css('position', 'absolute');
                        $(locker).css('top', '0px');
                        $(locker).css('left', '0px');
                        $(locker).css('height', this.getWindowDimension('height'));
                        $(locker).css('width', this.getWindowDimension('width'));
                        $(locker).css('z-index', 1);
                        $(locker).css('background', '#000');
        
                        if ($.browser.msie) {
                            $(locker).css('filter', 'alpha(opacity=40)');
                        } else {
                            $(locker).css('opacity', '0.40');
                        }
        
                        $('body').append(locker);
        
                        if (body.style.overflow != '') {
                            jinj.cache.store(body.style.overflow, 'body-overflow');
                        }
        
                        $('body').css('overflow', 'hidden');
                    }
                },
        
                unlockScreen: function()
                {
                    var body = this.getBody(window);
                    var cache = jinj.cache.read();
        
                    if ($('#locker').length >= 1) {
                        $('#locker').remove();
                    }
        
                    if (typeof(cache['body-overflow']) != 'undefined') {
                        $('body').css('overflow', cache['body-overflow']);
                    } else {
                        $('body').css('overflow', '');
                    }
        
                    return this;
                },
        
                openPopup: function(options, anchors)
                {
                    if ($('#popup').length < 1) {
                        var defaultWidth = 350, defaultHeight = 250;
        
                        var popup = document.createElement('div');
                            popup.id = 'popup';
        
                        if (typeof(options) == 'undefined') {
                            options = {};
                        }
                        
                        if (typeof(options.width) == 'undefined' || typeof(options.height) == 'undefined') {
                            options.width  = defaultWidth;
                            options.height = defaultHeight;
                        }
        
                        if (typeof(options.className) != 'undefined') {
                            popup.className = options.className;
                        }
        
                        $(popup).css('width', options.width);
                        $(popup).css('height', options.height);
                        $(popup).css('z-index', 2);
        
                        if (typeof(options.css) == 'object') {
                            for (style in options.css) {
                                $(popup).css(options.css[style][0], options.css[style][1]);
                            }
                        }
        
                        this.lockScreen();
        
                        $('body').append(popup);
                        $(popup).draggable({ cursor: 'move' });
                        this.centerElement(popup, false, true, anchors);
                    }
                },
        
                closePopup: function()
                {
                    if ($('#popup').length >= 1) {
                        $('#popup').remove();
                    }
        
                    this.unlockScreen();
                    void(0);
                },
            
	            openVaultPopup: function(id, vid)
	            {
	                (function(profile) {
	                    $.ajax({
	                        type: 'POST',
	                        url: '/core/profile/add-vault',
	                        data: {id:id,vid:vid},
	                        dataType: 'html',
	                        success: function(content) {
	                            application.openPopup({width: '520px', height: ''}, {top: -180, left: -92});
	                            var popup = $('#popup');
	                            popup.css('display', 'none');
	                            popup.html(content);
	                            popup.ready(function() {
	                                popup.css('display', 'block');
									$("#purchase_date, #expire_date").datepicker({
									    firstDay: 1,
									    dateFormat:'dd MM yy',
									    changeFirstDay: false,
									    prevText: "&laquo; Prev",
									    nextText: "Next &raquo;",
                                        beforeShow: customRangeDates
									});
	                            });
	                        }
	                    })
	                })(this);
	            }

            };

        window.application = new PoliceAgenda();
        window.application.feedbackFadeout();
        window.application.errorsFadeout();
        
        $('#show-hide').click(function() {
            if($('#show-hide').hasClass('expand')){
                $('#show-hide').removeClass('expand');
                $('#show-hide').addClass('collapse');
                $(this).next().slideUp('normal');
            } else {
                $('#show-hide').addClass('expand');
                $(this).next().slideDown('normal');
            }
        });
        
        $('#folder-show-hide').click(function() {
            if($('#folder-show-hide').hasClass('expand')){
                $('#folder-show-hide').removeClass('expand');
                $('#folder-show-hide').addClass('collapse');
                $('.folder-mail-list').slideUp('normal');
            } else {
                $('#folder-show-hide').addClass('expand');
                $('.folder-mail-list').slideDown('normal');
            }
        });
        
        $('#my-folder-show-hide').click(function() {
            if($('#my-folder-show-hide').hasClass('expand')){
                $('#my-folder-show-hide').removeClass('expand');
                $('#my-folder-show-hide').addClass('collapse');
                $('.my-folder-mail-list').slideUp('normal');
            } else {
                $('#my-folder-show-hide').addClass('expand');
                $('.my-folder-mail-list').slideDown('normal');
            }
        });

        $(window).bind('resize', function() {
            var popup = document.getElementById('popup');

            if ($('#locker').length == 1) {
                window.application.unlockScreen().lockScreen();
            }

            if (null !== popup) {
                window.application.centerElement(popup, false);
            }
        });
    }
);

function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

function customRangeDates(input) {
    return {
        minDate: (input.id == "expire_date" ? $("#purchase_date").datepicker("getDate") : null),
        maxDate: (input.id == "purchase_date" ? $("#expire_date").datepicker("getDate") : null)
    };
}
