/////////////////////////////////////////////////////////////////////////////
// APIEz Global JS
/////////////////////////////////////////////////////////////////////////////

// Youtube payer ready event
var onYouTubePlayerReady = function(playerId) {
    $.vid.watching(null, {step:4});
};

// JQuery
(function($) {
    /**
    * Define the browser type
    *
    * @var    string     userAgent Useragent string
    * @var    boolean    is_opera  Opera
    * @var    boolean    is_saf    Safari
    * @var    boolean    is_webtv  WebTV
    * @var    boolean    is_ie     Internet Explorer
    * @var    boolean    is_ie4    Internet Explorer 4
    * @var    boolean    is_ie7    Internet Explorer 7
    * @var    boolean    is_ps3    Playstation 3
    * @var    boolean    is_moz    Mozilla / Firefox / Camino
    * @var    boolean    is_kon    Konqueror
    * @var    boolean    is_ns     Netscape
    * @var    boolean    is_ns4    Netscape 4
    * @var    boolean    is_mac    Client is running MacOS
    */
    $.mb = {};
    var userAgent = navigator.userAgent.toLowerCase();
    $.mb.is_opera  = ((userAgent.indexOf('opera') != -1) || (typeof(window.opera) != 'undefined'));
    $.mb.is_saf    = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
    $.mb.is_webtv  = (userAgent.indexOf('webtv') != -1);
    $.mb.is_ie     = ((userAgent.indexOf('msie') != -1) && (!$.mb.is_opera) && (!$.mb.is_saf) && (!$.mb.is_webtv));
    $.mb.is_ie4    = (($.mb.is_ie) && (userAgent.indexOf('msie 4.') != -1));
    $.mb.is_ie7    = (($.mb.is_ie) && (userAgent.indexOf('msie 7.') != -1));
    $.mb.is_ps3    = (userAgent.indexOf('playstation 3') != -1);
    $.mb.is_moz    = ((navigator.product == 'Gecko') && (!$.mb.is_saf));
    $.mb.is_kon    = (userAgent.indexOf('konqueror') != -1);
    $.mb.is_ns     = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!$.mb.is_opera) && (!$.mb.is_webtv) && (!$.mb.is_saf));
    $.mb.is_ns4    = (($.mb.is_ns) && (parseInt(navigator.appVersion) == 4));
    $.mb.is_mac    = (userAgent.indexOf('mac') != -1);
    
    var oldone = ($.mb.is_ie && !$.mb.is_ie7) || ($.mb.is_ie && $.mb.is_mac) || $.mb.is_ie4 || $.mb.is_ns4;
    
    // AJAX setup
    $.ajaxSetup({
        global: false,
        type: "POST",
        dataType: "json"
    });
    
    // Search form
    $.sform = {
        // Form type changer
        ftype: function(th, mode, norm_elm, expn_elm){
            switch(mode){
                case 'norm':
                    $(expn_elm).fadeOut("fast", function(){
                        $(norm_elm).fadeIn("fast");
                    });
                    break;
                case 'expn':
                    $(norm_elm).fadeOut("fast", function(){
                        $(expn_elm).fadeIn("fast");
                    });
                    break;
                default:
                    return false;
            }
            
            $.ajax({
                mode: "abort",
                ch: "global",
                port: "sform",
                data: "act=ftype&v="+mode
            });
        },
        // Search mode changer
        smode: function(th, mode, ft_btn, strc_btn, ft_elm, strc_elm){
            switch(mode){
                case 'fulltext':
                    $(strc_elm).fadeOut("fast", function(){
                        $(strc_btn).removeClass("selected");
                        $(ft_btn).addClass("selected");
                        $(ft_elm).fadeIn("fast");
                    });
                    break;
                case 'structured':
                    $(ft_elm).fadeOut("fast", function(){
                        $(ft_btn).removeClass("selected");
                        $(strc_btn).addClass("selected");
                        $(strc_elm).fadeIn("fast");
                    });
                    break;
                default:
                    return false;
            }
            
            $.ajax({
                mode: "abort",
                ch: "global",
                port: "smode",
                data: "act=smode&v="+mode
            });
            
        }
    };
    
    // Lightbox
    $.lightbox = {
        text: {
            close:        'Close X',
            closeInfo:    'You can also click anywhere outside the image to close.',
            help: {
                close:        'Click to close',
                interact:    'Hover to interact'
            }
        },
        images: {
            blank:        img + 'blank.gif',
            loading:    img + 'loading.gif'
        },
        opacity: 0.85,
        speed: 400,    // Duration of effect, milliseconds
        onshow: false,
        init: function() {
            // Append markup
            $('body').append('<div id="lightbox-overlay"><div id="lightbox-overlay-text"><p><span id="lightbox-overlay-text-close">'+this.text.help.close+'</span></p></div></div><div id="lightbox"><div id="lightbox-imageBox"><div id="lightbox-imageContainer"><div id="lightbox-image"></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + this.images.loading + '" /></a></div></div></div></div>');
            
            // Update Boxes - for some crazy reason this has to be before the hide in safari and konqueror
            this.resizeBoxes();
            this.repositionBoxes();
            
            // Hide
            $('#lightbox,#lightbox-overlay').hide();
            
            // If the window resizes, act appropriatly
            $(window).resize(function () { $.lightbox.resizeBoxes(); $.lightbox.repositionBoxes(); });
            
            // Assign close clicks
            $('#lightbox-overlay, #lightbox, #lightbox-loading-link').unbind().click(function() {
                $.lightbox.finish();
                return false;    
            });
        },
        getPageScroll: function () {
            var xScroll, yScroll;
            if (self.pageYOffset)
            {    // Some browser
                yScroll = self.pageYOffset;
                xScroll = self.pageXOffset;
            } else if (document.documentElement && document.documentElement.scrollTop)
            {    // Explorer 6 Strict
                yScroll = document.documentElement.scrollTop;
                xScroll = document.documentElement.scrollLeft;
            } else if (document.body)
            {    // All other browsers
                yScroll = document.body.scrollTop;
                xScroll = document.body.scrollLeft;    
            }
            var arrayPageScroll = {'xScroll':xScroll,'yScroll':yScroll};
            return arrayPageScroll;
        },
        resizeBoxes: function () {
            // Style overlay and show it
            $('#lightbox-overlay').css({
                width: $(document).width(),
                height: $(document).height()
            });
        },
        repositionBoxes: function (options) {
            // Options
            options = $.extend({}, options);
            options.callback = options.callback || null;
            options.speed = options.speed || 'slow';
            
            // Get page scroll
            var pageScroll = this.getPageScroll();
            
            // Figure it out
            var nHeight = options.nHeight || parseInt($('#lightbox').height(),10) || $(document).height()/3;
            
            // Display lightbox in center
            var nTop = pageScroll.yScroll + ($(document.body).height() /*frame height*/ - nHeight) / 2.5;
            var nLeft = pageScroll.xScroll;
            
            // Animate
            var css = {
                left: nLeft,
                top: nTop
            };
            if (options.speed) {
                $('#lightbox').animate(css, 'slow', options.callback);
            }
            else
            {
                $('#lightbox').css(css);
            }
            
            // Done
            return true;
        },
        start: function (html, callback) {    // Display the lightbox
            
            // On show
            $.lightbox.onshow = true;
            
            // Fix attention seekers
            $('embed, object, select').css('visibility', 'hidden');//.hide(); - don't use this, give it a go, find out why!
            
            // Resize the boxes appropriatly
            this.resizeBoxes();
            
            // Reposition the Boxes
            this.repositionBoxes({'speed':0});
            
            // Hide things
            $('#lightbox-image').hide();
                    
            // Display the boxes
            $('#lightbox-overlay').css('opacity',this.opacity).fadeIn(400, function(){
                // Show the lightbox
                $('#lightbox').fadeIn(300);
                
                if(html)
                    $('#lightbox-image').html(html);
                else
                    $('#lightbox-image').html('');
                
                if(typeof callback == 'function')
                    callback();
            });
            
            // All done
            return true;
        },
        finish: function () {    // Get rid of lightbox
            // Not on show
            $.lightbox.onshow = false;

            $('#lightbox').hide();
            $('#lightbox-overlay').fadeOut(function() { $('#lightbox-overlay').hide(); });
            $('#lightbox-image').empty();
            // Fix attention seekers
            $('embed, object, select').css({ 'visibility' : 'visible' });//.show();
            if($.tn && $.tn.preloader)
                $.tn.preloader = {};
        },
        pause: function ( ms ) {
            var date = new Date();
            var curDate = null;
            do { curDate = new Date(); }
            while ( curDate - date < ms);
        }
    };
    
    // Images thumbnail
    $.tn = {
        data: {},
        cur: {},
        preloader: {},
        nav: function(th, mod, id) {
            var tnd = this.data[id];
            if(tnd){
                if(typeof this.cur[id] === 'undefined')
                    this.cur[id] = 0;
                
                var iid = this.cur[id];
                switch(mod) {
                    case 'prev':
                        if(iid-1 < 0)
                            iid = tnd.length-1;
                        else
                            iid = iid-1;
                        break;
                    case 'next':
                        if(iid+1 > (tnd.length-1))
                            iid = 0;
                        else
                            iid = iid+1;
                        break;
                }
                this.cur[id] = iid;
                $('#thumbnail_'+id).attr('href', tnd[iid]);
                $('#thumbnail_'+id+' img').attr('src', tnd[iid]);
            }
        },
        view: function(th, mod, id) {
            var vimg = null;
            switch(mod) {
                case 'singleview':
                    vimg = $(th).attr('href');
                    break;
                case 'multiview':
                    var tnd = this.data[id];
                    if(tnd) {
                        if(typeof this.cur[id] === 'undefined')
                            this.cur[id] = 0;
                        
                        var iid = this.cur[id];
                        vimg = tnd[iid];
                    } else {
                        vimg = $(th).attr('href');
                    }
                    break;
                default:
                    return false;
            }
            
            if(!vimg) return false;
            
            if(oldone) {
                var _popup_img = window.open("","","toolbar=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=600");
                _popup_img.document.write('<head><title>Thumbnail viewer</title></head><body style="margin:0;padding:0;"><center><img src="'+vimg+'" /></center></body></html>');
                _popup_img.document.close();    
            } else {
                $.lightbox.start('<img id="viewimg" />', function() {
                    $.tn.viewstep(vimg);
                });
            }
        },
        viewstep: function(image, options) {
            // Establish options
            options = $.extend({step:1}, options);
            
            // What do we need to do
            switch (options.step)
            {
                // ---------------------------------
                // We need to preload
                case 1:
                    // Show the loading image
                    $('#lightbox-loading').show();
                    
                    // Hide things
                    $('#lightbox-image').hide();
                    
                    // Remove show info events
                    $('#lightbox-imageBox').unbind();
                    // ^ Why? Because otherwise when the image is changing, the info pops out, not good!
                    
                    // Preload the image
                    $.tn.preloader = new Image();
                    $.tn.preloader.onload = function() {
                        if($.lightbox.onshow === true) {
                            $.tn.viewstep(image, {step:2, width:$.tn.preloader.width, height:$.tn.preloader.height});

                            $.tn.preloader.onload = null;
                            $.tn.preloader = null;
                        }
                    };
                    $.tn.preloader.src = image;
                    
                    // Done
                    break;
                // ---------------------------------
                // Resize the container
                case 2:
                    
                    // Set image src
                    $('#lightbox-image #viewimg').attr('src', image);
                    
                    // Establish options
                    options = $.extend({width:null, height:null}, options);
                    
                    // Set container border (Moved here for Konqueror fix - Credits to Blueyed)
                    var padding = parseInt($('#lightbox-imageContainer').css('padding-left'), 10) || parseInt($('#lightbox-imageContainer').css('padding'), 10) || 0;
                    
                    // Resize image box
                    // i:image, c:current, n:new, d:difference
                    
                    // Get image dimensions
                    var iWidth  = options.width;
                    var iHeight = options.height;
                    
                    // Get current width and height
                    var cWidth = $('#lightbox-imageBox').width();
                    var cHeight = $('#lightbox-imageBox').height();
            
                    // Get the width and height of the selected image plus the padding
                    var nWidth    = (iWidth  + (padding * 2)); // Plus the image's width and the left and right padding value
                    var nHeight    = (iHeight + (padding * 2)); // Plus the image's height and the left and right padding value
                    
                    // Diferences
                    var dWidth  = cWidth  - nWidth;
                    var dHeight = cHeight - nHeight;
                    
                    // Reposition the Boxes
                    $.lightbox.repositionBoxes({'nHeight':nHeight});
                    
                    // Do we need to wait? (just a nice effect to counter the other
                    if ( dWidth === 0 && dHeight === 0 )
                    {    // We are the same size
                        if ( $.browser.msie ) {
                            $.lightbox.pause(250);
                        } else {
                            $.lightbox.pause(100);    
                        }
                        $.tn.viewstep(null, {step:3});
                    }
                    else
                    {    // We are not the same size
                        // Animate
                        $('#lightbox-imageBox').animate({ width: nWidth, height: nHeight }, $.lightbox.speed, function () {
                            $.tn.viewstep(null, {step:3});
                        });
                    }
                    
                    // Done
                    break;
                // ---------------------------------
                // Display the image
                case 3:
                    
                    // Hide loading
                    $('#lightbox-loading').hide();
                    
                    // Animate image
                    $('#lightbox-image').fadeIn(500, function() {
                        //$.Lightbox.showImage(null, {step:4});
                    });
                    
                    // Done
                    break;
            }
        }
    };
    
    // Video in page view
    $.vid = {
        watching: function(vid, options) {
            // Establish options
            options = $.extend({step:1}, options);
            
            // What do we need to do
            switch (options.step)
            {
                case 1:
                    if(oldone) {
                        var _popup_vid = window.open("","","toolbar=no,menubar=no,scrollbars=no,resizable=yes,width=430,height=360");
                        _popup_vid.document.write('<head><title>Watch video</title></head><body style="margin:0;padding:0;"><object width="425" height="355"><param name="movie" value="'+vid+'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/bv8a4fXoLCI" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></embed></object></body></html>');
                        _popup_vid.document.close();
                    } else {
                        options = $.extend(options, {step:2});
                        $.lightbox.start(null, function(){
                            $.vid.watching(vid, options);
                        });
                    }
                    
                    break;
                case 2:
                    // Show the loading image and the img
                    $('#lightbox-loading, #lightbox-image').show();
                    
                    // Remove show info events
                    $('#lightbox-imageBox').unbind();
                    
                    // Establish options
                    options = $.extend({width:425, height:356}, options);
                    
                    // Set container border (Moved here for Konqueror fix - Credits to Blueyed)
                    var padding = parseInt($('#lightbox-imageContainer').css('padding-left'), 10) || parseInt($('#lightbox-imageContainer').css('padding'), 10) || 0;
                    
                    // Resize image box
                    // i:image, c:current, n:new, d:difference
                    
                    // Get image dimensions
                    var iWidth  = options.width;
                    var iHeight = options.height;
                    
                    // Get current width and height
                    var cWidth = $('#lightbox-imageBox').width();
                    var cHeight = $('#lightbox-imageBox').height();
            
                    // Get the width and height of the selected image plus the padding
                    var nWidth    = (iWidth  + (padding * 2)); // Plus the image's width and the left and right padding value
                    var nHeight    = (iHeight + (padding * 2)); // Plus the image's height and the left and right padding value
                    
                    // Diferences
                    var dWidth  = cWidth  - nWidth;
                    var dHeight = cHeight - nHeight;
                    
                    // Reposition the Boxes
                    $.lightbox.repositionBoxes({'nHeight':nHeight});
                    
                    // Do we need to wait? (just a nice effect to counter the other
                    if ( dWidth === 0 && dHeight === 0 )
                    {    // We are the same size
                        if ( $.browser.msie ) {
                            $.lightbox.pause(250);
                        } else {
                            $.lightbox.pause(100);    
                        }
                        $.vid.watching(vid, {step:3});
                    }
                    else
                    {    // We are not the same size
                        // Animate
                        $('#lightbox-imageBox').animate({ width: nWidth, height: nHeight }, $.lightbox.speed, function () {
                            $.vid.watching(vid, {step:3});
                        });
                    }
                    break;
                case 3:
                    $('#lightbox-image').html('<div id="vidembed" style="padding-top:150px;line-height:20px;"><center><span style="font-weight:bold;">You need Flash player 8+ to view this video.</span><br /><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></center></div>');
                    var params = {
                        allowScriptAccess: "always",
                        menu: "false",
                        flashvars: "border=0&enablejsapi=1&playerapiid=ytplayer"
                    };
                    var atts = {id: "myytplayer"};
                    swfobject.embedSWF(vid, "vidembed", "425", "356", "8", img+"expressInstall.swf", null, params, atts);
                    break;
                // ---------------------------------
                // Display the video
                case 4:
                    // Hide loading
                    $('#lightbox-loading').hide();
                    $('#lightbox-imageBox').click(function() {
                        return false;    
                    });
                    // Done
                    break;
            }
        }
    };
    
    // On document load
    $(function() {
        $.lightbox.init();
    });
    
})(jQuery);