﻿// This is just here to tell JS lint that we need to use a global variable
/*global TVI, loadFirebugConsole, document, alert, console, window $ */

/*
    TVI Framework
    Version 1.0
    Copywrite 2009 TVI Design
    Last Updated: 10/11/2009
    
    Contents:
        TVI.Popup
*/

TVI.Popup = function() {

    /* Private */

    /* Properties */

    var cmp = {};
    
    var buttons = [];
    var template = '' +
    
        '<div class="TVI-popup-border">' +
            '<div class="TVI-popup-inner">' +
                '<div class="TVI-popup-header">' +
                    '<div class="TVI-popup-close"><a href="#"></a></div>' +
                    '<h5>${title}</h5>' +
                    '<div class="clear"></div>' +
                '</div>' +
                '<div class="TVI-popup-main">' +
                    
                        '${template}' +
                    
                '</div>' +
                '<div class="TVI-popup-footer">' +
                    
                    '{for b in buttons}' +
                        '<a class="${b.cls}" href="#">${b.text}</a> ' +
                    '{/for}' +
                    
                    '<div class="clear"></div>' +
                        
                '</div>' +
            '</div>' +
        '</div>';
        
    var templates = {};





    /* Methods */

    var init = function() {

        // Find the popup div
        cmp.el = $('#TVI-popup');
        
        //check element exists
        if (cmp.el.length === 0){ 
        
            cmp.el = $('<div id="TVI-popup"></div>');
            
            $('BODY').append(cmp.el);
            
        }
        
        
        //hide any templates
        $('.TVI-popup-templates').hide();
        
        
        //show modal if required
        if (cmp.modal === true){
                
            cmp.el.jqm({
            
                modal: true,
                overlay: cmp.overlay
            
            });
        
        }
        
        
        //check templating exists
        if (''.process === undefined){
        
            TVI.logWarning('TVI.Popup : trimpath-template.js required');
        
            return;
        
        }
        

        // Add hide functionality to all close buttons.
        TVI.event('#TVI-popup .TVI-popup-close A', 'click', close);
        
        
        //handle popup button clicks
        TVI.event('#TVI-popup .TVI-popup-footer A', 'click', buttonClicked);

    };
    
    
    
    
    
    var buttonClicked = function(){
    
        /* Handles a popup button click */
    
        //get the index of the button
        var index = cmp.el.find('.TVI-popup-footer A').index(this);
        
        //check the buttons array if more than the index
        if (buttons.length <= index){ return; }
        
        //call button handler if exists
        if (buttons[index].handler !== undefined){
        
            buttons[index].handler.call(cmp);
        
        }
    
    };





    var close = function() {
        
        /* Hide the popup */
    
        cmp.el.hide();
        
        
        //show modal if required
        if (cmp.modal === true){
        
            cmp.el.jqmHide();
        
        }
        
        TVI.fireEvent('TVI.Popup.close', cmp);
        
    };
    
    
    
    
    
    var confirm = function(params){
    
        /* Shows a list of errors to the user */        
        
        TVI.apply(params, {
        
            buttons: [{
            
                text: 'Cancel',
                handler: close
            
            },{
            
                text: 'Confirm',
                handler: function(){
                
                    if (params.autoClose !== false){
                
                        close();
                    
                    }
                    
                    params.handler.call();
                
                }
            
            }]
        
        });
        
        show(params);
    
    };
    
    
    
    
    
    var error = function(errors){
    
        /* Shows a list of errors to the user */
    
        if (!errors || errors.length === 0){ return; }
        
        
        var html = '' +
            
            '{for e in errors}' +
                '<p class="error">* ${e.message}.</p>' +
            '{/for}';
            
        html = html.process({ errors: errors });
        
        
        show({
        
            title: 'Oops!',
            template: html,
            buttons: [{
            
                text: 'Close',
                handler: close
            
            }]
        
        });
    
    };





    var layout = function(params) {
    
        /* Resize and reposition the popup */

        // Get the popup width or use the default
        var popupWidth = params.width || cmp.width;

        // Get the position of the left hand side of the popup
        var viewportWidth = $(window).width();
        var leftPosition = (viewportWidth - popupWidth) / 2;

        // Get the top margin or use the default
        var topPosition = ($(window).height() / 2) - (cmp.el.height() / 2) + $(window).scrollTop();
        
        //stop popup going above the page
        if (topPosition < 10){ topPosition = 10; }
        
        // Apply the changes
        cmp.el.css({
            'width': popupWidth + 'px',
            'left': leftPosition + 'px',
            'top': topPosition + 'px'
        });

    };





    var show = function(params) {

        /* Show the popup */
        
        //set defaults
        TVI.apply(params, {
            
            buttons: params.buttons !== undefined ? params.buttons : null,
            template: params.template !== undefined ? params.template : null,
            title: params.title !== undefined ? params.title : null
        
        });
        

        //get popup template if necessary        
        if (params.template && params.template.indexOf(' ') < 0){
        
            //check template doesn't already exist
            if (templates[params.template] === undefined){
            
                //get template element and check it exists
                var templateEl = $('.TVI-popup-templates #' + params.template);
                
                if (templateEl.length === 0){ 
                
                    TVI.logError({ code: '100', message: 'TVI.Popup : template ' + params.template + ' doesn\'t exist' }); 
                    
                    return;
                    
                }
                
                //save template
                templates[params.template] = templateEl.html();
                                            
            }
        
            //add html to params for binding to template
            params.template = templates[params.template];
        
        }
                

        //bind template to given params and set popup html
        var html = template.process(params);
        
        cmp.el.html(html);
        
        
        //if title not passed in, use H5 in template html
        if (!params.title){

            var titleEl = cmp.el.find('.TVI-popup-main H5:first');
                
            if (titleEl.length > 0){
                    
                cmp.el.find('.TVI-popup-header H5:first').replaceWith(titleEl);
            
            }
        
        }
        
        
        //set buttons from params or empty array
        buttons = params.buttons ? params.buttons : [];
        
        
        if (buttons.length > 0){
        
            cmp.el.find('.TVI-popup-footer').show();
        
        }
        else{
            cmp.el.find('.TVI-popup-footer').hide();
        }
        
        
        //hide close button if specified
        if (params.closable === false){
        
            cmp.el.find('.TVI-popup-close').hide();
        
        }
        else{
        
            cmp.el.find('.TVI-popup-close').show();
            
        }
        
        
        // Resize and reposition the popup
        layout(params);
        
        
        //show modal if required
        if (cmp.modal === true){
        
            cmp.el.jqmShow();
        
        }
        else{
        
            cmp.el.show();
        
        }
        
                
        //do callback
        if (params.success !== undefined){
        
            params.success.call(cmp);
        
        }
        
        
        //fire event
        TVI.fireEvent('TVI.Popup.onShow', cmp);//outdated
        TVI.fireEvent('TVI.Popup.show', cmp);
        
    };
    
    
    
    
    
    var setTemplate = function(t){
    
        template = t;
    
    };





    /* Public */

    TVI.apply(cmp, {

        /* Properties */
        
        modal: true,
        overlay: 50,        
        width: 600,
        
        /* Methods */

        close: function() {
        
            close();
            
        },

        confirm: function(params) {
        
            confirm(params);
            
        },

        error: function(errors) {
        
            error(errors);
            
        },

        show: function(params) {
        
            show(params);
            
        },

        setTemplate: function(t) {
        
            setTemplate(t);
            
        }

    });


    TVI.ready(init);


    return cmp;
    

} ();











/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 03/01/2009 +r14
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};

$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);
