/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 * Rewrited by Mati - mati@lellealternatiiv.ee / mati@we.ee
*/
$.thickbox = (function($) {
    var
    TB = this,
    MV_defaults = {
        load: {
           controller : 'general',
           action : 'loadtemplate',
           url :  false,
           template : null,
           uniq : '',
           type : 'json',           
           wrapIframe : false,
           width : null,//needed and used for Iframe only
           height : null,//needed and used for Iframe only
           buttons : '',//needed and used for Iframe only                                  
           data : null //function or {}, 
        }, //function
        onContentClose: null, //function
        beforeShown : null, //function
        contentSelector: null, //may also be htmlstring;
        closeSelector: '.TBclose',
        closeOnEscOrClick: true,
        cloneContent: false,
        closeTime : 0
    },
    MV_cfg = {
        idClassPrefix : 'thickboxid_',
        hideSelectId: 'TB_HideSelect',
        overlayId: 'TB_overlay',
        overlayMacFFBGHackClass: 'TB_overlayMacFFBGHack',
        overlayBGClass : 'TB_overlayBG',
        contentClass: 'TB_contentClass',
        iframeId: 'TBiframe'        
    },
    MV_isIe6 = (navigator.userAgent.indexOf('MSIE 6.0') == -1)? false : true,
    MV_isIe8 = (navigator.userAgent.indexOf('MSIE 8.0') == -1)? false : true,    
    MV_isMac = (function() {
        var ua = navigator.userAgent.toLowerCase();
        return (ua.indexOf('mac') != -1 && ua.indexOf('firefox') != -1);
    })(),
    MV_closeTimeout = null,
    MV_target = null,
    MV_currentOptions = null,
    MV_settings = {},
    MV_loadedTemplates = {},
    MF_stringtoint = function(string) {
        var result = 0;
        for(var i=0; i < string.length; i++)
           result += string.charCodeAt(i);
        return result;
    },
    MF_setting = function (param) {
        var data = MV_currentOptions? MV_currentOptions : MV_defaults;
        return param? data[param] : data;
    },
    MF_getId = function(target) {
        var classes = $(target).attr('class').split(' ');
        var pl = MV_cfg.idClassPrefix.length;
        for (var i = 0, l = classes.length; i < l; i++ ) {
            if (classes[i].length > pl && classes[i].substr(0, pl) == MV_cfg.idClassPrefix) {
                return classes[i].substr(pl);
            }
        }
    },
    MF_removeContent = function() {
        if ($.isFunction(MF_setting('onContentClose')))
            MF_setting('onContentClose').call(this);
        if (MF_setting('cloneContent')) {
            $('.'+ MV_cfg.contentClass).remove();
        } else {
            $('.'+ MV_cfg.contentClass).hide();
            $('.'+ MV_cfg.contentClass).removeClass(MV_cfg.contentClass);
        }
    },

    MF_closeonerror = function(error) {
        if (MV_closeTimeout)
            clearTimeout(MV_closeTimeout);
        $('#' + MV_cfg.overlayId + ',#' + MV_cfg.hideSelectId).unbind().remove();
        MF_removeContent();
        MV_currentOptions = null;
        $.loadingIndicator.stop();          
        if (confirm("  Error" + (error? ': ' + error : '') + "\nReload page?")) 
            document.location.reload();
            
    },    
    
    MF_close = function () {
        $('.'+ MV_cfg.contentClass)
            .fadeOut("fast", function(){
                if (MV_closeTimeout)
                    clearTimeout(MV_closeTimeout);
                $('#' + MV_cfg.overlayId + ',#' + MV_cfg.hideSelectId).unbind().remove();
                MF_removeContent();
                MV_currentOptions = null;
            });
        return false;
    },

    MV_load = function (options, target) {
    
        var l = options.load, key = MF_stringtoint(String(l.controller + l.action + l.template + l.uniq));
        if (l.type == 'ajax') { 
           if (l.wrapIframe) {
               var
               id = 'TB' + $.unique_id(),
               url = l.url? l.url : (BASEURL + 'ajax.php?' + jQuery.param( {controller : l.controller, action : l.action, template : l.template, uniq : l.uniq, data : $.isFunction(l.data)? l.data(target) : l.data, key : key})),
               h = (l.height || 300), w = (l.width || 300),  
               s = ['display : block', 'width : ' + w + 'px', 'height : ' + h + 'px', 
                   'margin-left : -' + (w / 2) + 'px', 
                   'margin-top : ' + (-(h / 2) + ($("html").scrollTop() || $("body").scrollTop())) + 'px'];               
               TB_showIframe_init = function () {
                   this.onload = function(){};
                   options.contentSelector = '#' + id;                   
                   TB_showIframe(options, target);
                   delete TB_showIframe_init;                                                
               };                                              
               $("body").append(
                  '<div class="TBwindow ' + MV_cfg.contentClass + '" id="' + id + '" style="' + s.join('; ') + '; ">' +
                  '<a class="TBcloseTop TBclose" href=""></a>' +                    
                  '<iframe FRAMEBORDER="0" scrolling="no" src=" ' + url + '" style="height : ' + (h - 0) + 'px;" id="' + MV_cfg.iframeId + '" onload="TB_showIframe_init.call(this);"> </iframe>' +
                  '<div class="buttons">' + l.buttons + '</div>' +                    
                  '</div>'
               );           
           } else {
              if (MV_loadedTemplates[key]) {
                  options.contentSelector = MV_loadedTemplates[key];
                  options.cloneContent = false;//no point
                  MV_show(options, target);
              } else {           
                  $.ajax({
                      url : BASEURL + 'ajax.php?controller=' + l.controller + '&amp;action=' + l.action,
                      data : {template : l.template, data : $.isFunction(l.data)? l.data(target) : l.data, key : key},
                      cache : false,
                      success: function(html){
                           MV_loadedTemplates[key] = key;
                           options.contentSelector = html;
                           options.cloneContent = false;//no point
                           MV_show(options, target);
                      }
                  });    
               }       
           }
          
        } else {
    
            if (MV_loadedTemplates[key]) {
                options.contentSelector = MV_loadedTemplates[key];
                options.cloneContent = false;//no point
                MV_show(options, target);
            } else {
               $.post(BASEURL + 'json.php?controller=' + l.controller + '&action=' + l.action,
                   {template : l.template, data : $.isFunction(l.data)? l.data(target) : l.data, key : key}, function(j){
                       if (j && j.html) {
                           MV_loadedTemplates[key] = j.html;
                           options.contentSelector = j.html;
                           options.cloneContent = false;//no point
                           MV_show(options, target);
                       } else {
                           options.json = j;
                           MF_closeonerror((j && j.error)? j.error : null);                           
                           return;
                       }
                }, 'json');
            }
        }
    },

    MV_show = function (options, target) {
    
        MV_currentOptions = options;
        MV_target = target;
        var obj, contentIframe;                
        if (MF_setting('cloneContent')) {
           obj = $(MF_setting('contentSelector')).clone(true);
           obj.appendTo('body');           
        } else if (MF_setting('load')) {
        
            if (MF_setting('load').wrapIframe) {            
               obj = $(MF_setting('contentSelector'));            
            } else {
               obj = $(MF_setting('contentSelector'));
               obj.appendTo('body');            
            }
        } else {
           obj = $(MF_setting('contentSelector'));
           obj.appendTo('body');           
        }

        if (!obj.get(0)) {
           MF_closeonerror();           
           return;
        }

        if ($.isFunction(MF_setting('beforeShown')))
            MF_setting('beforeShown').call(this, obj, MV_target);
            
        obj.addClass(MV_cfg.contentClass).show();

        obj.css({
            marginLeft: '-' + parseInt((obj.width() / 2), 10) + 'px',
            marginTop : -parseInt((obj.height() / 2) , 10) + ($("html").scrollTop() || $("body").scrollTop()) + 'px'
        });

        if (MF_setting('closeSelector')) {
            obj.find(MF_setting('closeSelector')).click(function(e){
                e.preventDefault(e);
                MF_close();
            });
        }

        if (MV_closeTimeout)
            clearTimeout(MV_closeTimeout);
        var ms = 1000 * parseFloat(MF_setting('closeTime'));
        if (ms)
            MV_closeTimeout = setTimeout(function(){MF_close()}, ms);
        $.loadingIndicator.stop();
    },
    
     TB_showIframe = function(options, target){

        MV_currentOptions = options;
        MV_target = target;
                
        var obj = $(MF_setting('contentSelector')); 
        
        if ($.isFunction(MF_setting('beforeShown')))
            MF_setting('beforeShown').call(this, obj, MV_target);    
        if (MF_setting('closeSelector')) {
            obj.find(MF_setting('closeSelector')).click(function(e){
                e.preventDefault(e);
                MF_close();
            });
        }

        if (MV_closeTimeout)
            clearTimeout(MV_closeTimeout);
        var ms = 1000 * parseFloat(MF_setting('closeTime'));
        if (ms)
            MV_closeTimeout = setTimeout(function(){MF_close()}, ms);
        $.loadingIndicator.stop();                                     
     },      

    MF_init = function (options, target) {
        $.loadingIndicator.init(true);
        if (!MV_currentOptions) {
            if (MV_isIe6) {//if IE 6
                if (document.getElementById(MV_cfg.hideSelectId) === null) {//iframe to hide select elements in ie6
                    $("body").append('<iframe id="' + MV_cfg.hideSelectId + '"></iframe><div id="' + MV_cfg.overlayId + '"></div>');
//                    $('#' + MV_cfg.overlayId).height($('#' + MV_cfg.overlayId).height() + $("html").scrollTop())
                    $('#' + MV_cfg.overlayId).height($('body').height())
                    .click(function(){
                        if (MF_setting('closeOnEscOrClick'))
                            MF_close()
                    });
                }
            } else {//all others
                if(document.getElementById(MV_cfg.overlayId) === null){
                    $("body").append('<div id="' + MV_cfg.overlayId + '"></div>');
                    $('#' + MV_cfg.overlayId).click(function(){
                        if (MF_setting('closeOnEscOrClick'))
                            MF_close()
                    });
                }
            }
            //use png overlay so hide flash if mac : use background and opacity
            $('#' + MV_cfg.overlayId).addClass(MF_setting(MV_isMac? MV_cfg.overlayMacFFBGHackClass : MV_cfg.overlayBGClass));
            (options.load)? MV_load(options, target) : MV_show(options, target);
        } else {
            //set before if called from inside thickboxcontent;
            $('.'+ MV_cfg.contentClass)
                .fadeOut("fast", function(){
                    MF_removeContent();
                    (options.load)? MV_load(options, target) : MV_show(options, target);

                });
        }
    };

    $(document).keyup = function(e){
        if (MF_setting('closeOnEscOrClick')) {
            if (e == null)  // ie
                keycode = event.keyCode;
            else  // mozilla
                keycode = e.which;
            if(keycode == 27) // close
                MF_close();
        }
    };

    $.fn.thickbox = function(options){
        return this.each(function() {
            var uid = $.unique_id();
            var s = $.extend({}, MV_defaults, options);
            if (options.load)
                s.load = $.extend({}, MV_defaults.load, options.load)            
            if (s.contentSelector || s.load) {
                if (s.contentSelector)
                    $(s.contentSelector).appendTo('body');

                MV_settings[uid] = s;

                $(this).click(function(e) {
                    e.preventDefault();
                    var id = MF_getId(this);
                    MF_init((id && MV_settings[id])? MV_settings[id] : MV_defaults, this);
                    $(this).blur();
                }).unload(function(){
                    delete MV_settings[MF_getId(this)];
                });
                $(this).addClass(MV_cfg.idClassPrefix + uid);
            }
        });
    };
    return {
        show: function() { // selector, options or options
            var arg = $.makeArray(arguments), options = {}, contentSelector, settings;
            
            for (var i = 0; i<= 2; i++) {
                try {
                    switch (true) {
                        case (typeof arg[i] == 'object'): options = arg[i]; break;
                        case (typeof arg[i] == 'string' || $(arg[i]).get(0)): contentSelector = arg[i]; break;
                    }
                } catch (e) {
                }
            }
            if (contentSelector)
               options.contentSelector = contentSelector;

            settings = $.extend(true, {}, MV_defaults, options);
            settings.load = options.load? $.extend({}, MV_defaults.load, options.load) : false;             
            MF_init(settings);
        },
        close: function() {
            MF_close();
        }

    };

})(jQuery);

