﻿/*
    Popcorn version 1.0 - © Copyright 2009 by Isotop AB
    Info: Popcorn is an expanded version of Thickbox. 
    Author: Björn Lennartsson



    ::: Usage :::

    a. To load a image popup gallery (if you do not wan't a gallery you just remove the rel-attribute)
    1. <a href="SOURCE_TO_BIG_IMAGE" class="popcorn" rel="gallery"><img src="THUMB" /></a>
    2. FINISHED!

    b. To load Iframed content
    1. <a href="SOURCE_URL?TB_iframe=true&KeepAlive=true&width=XXX&height=YYY" class="popcorn">IFRAME POP</a>
    2. Erhh, FINISHED!

    c. To load a specific div, any possible who is located on the current page.
    1. On the element that is supposed to pop it, put following: onclick="Popcorn.Pop('DIVS ID/CLASS', null, null);return false;"
    2. You will need to have a button in the div so you can close the overlay, add following: onclick="Popcorn.Close();return false;"
    3. The div should have it's style attribute with display:none, THIS IS IMPORTANT!  
    
*/


var Popcorn = {

    _loaderImg: "/media/gfx/loader.gif",
    _imgPreLoader: null,
    _parentObject: null,
    _currentObject: null,

    Init: function() {
        Popcorn._imgPreLoader = new Image();
        Popcorn._imgPreLoader.src = Popcorn._loaderImg;

        jQuery('a.popcorn').click(function() {
            var action = this.rev || null;
            var a = this.href || this.alt;
            var g = this.rel || false;
            Popcorn.Pop(null, a, g);
            this.blur();
            return false;
        });
    },

    Pop: function(action, url, group) {
        try {

            // Check if we are browsing with <= IE6, because we will need to tweak behaviour i.e. hide select-boxes and set height of overlay.
            if (typeof document.body.style.maxHeight === "undefined") {
                jQuery("body", "html").css({ height: "100%", width: "100%" });
                jQuery("html").css("overflow", "hidden");
                if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
                    jQuery("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                    jQuery("#TB_overlay").click(Popcorn.Close);
                }
            }
            else {
                if (document.getElementById("TB_overlay") === null) {
                    jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
                    jQuery("#TB_overlay").click(Popcorn.Close);
                }
            }

            // Check if we are browsing with Mac + Firefox because then we will have to use a transparent PNG instead (to hide flash-content)...
            if (Popcorn.DetectIfMacFirefox())
                jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");
            else
                jQuery("#TB_overlay").addClass("TB_overlayBG");

            // Add our loader image
            jQuery("body").append("<div id='TB_load'><img src='" + Popcorn._imgPreLoader.src + "' /></div>");
            jQuery('#TB_load').show();

            if (action == null) {
                var baseURL;
                if (url.indexOf("?") !== -1) { //ff there is a query string involved
                    baseURL = url.substr(0, url.indexOf("?"));
                } else {
                    baseURL = url;
                }

                var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
                var urlType = baseURL.toLowerCase().match(urlString);

                // Check if we are dealing with images or other content
                if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp') {
                    TB_PrevURL = "";
                    TB_PrevHTML = "<div id='TB_prev_btn'><img src='/media/gfx/zoom_prev.gif' alt='Föregående' id='TB_prev' /></div>";

                    TB_NextURL = "";
                    TB_NextHTML = "<div id='TB_next_btn'><img src='/media/gfx/zoom_next.gif' id='TB_next' alt='Nästa' /></div>";

                    TB_imageCount = "";

                    TB_FoundURL = false;
                    TB_StartURL = "";
                    TB_EndURL = "";

                    TB_TempArray = [];

                    var initiated = false;

                    // If we are dealing with a image gallery
                    if (group) {
                        TB_TempArray = jQuery("a[rel=" + group + "]").get();

                        for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && TB_NextURL === ""); TB_Counter++) {
                            var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
                            if (!(TB_TempArray[TB_Counter].href == url)) {
                                if (TB_FoundURL) {
                                    TB_NextURL = TB_TempArray[TB_Counter].href;
                                } else {
                                    TB_PrevURL = TB_TempArray[TB_Counter].href;
                                }
                            } else {
                                TB_FoundURL = true;
                                TB_imageCount = "Bild " + (TB_Counter + 1) + " av " + (TB_TempArray.length);
                            }

                            if (!initiated) {
                                TB_StartURL = TB_TempArray[0].href;
                                TB_EndURL = TB_TempArray[TB_TempArray.length - 1].href;
                                initiated = true;
                            }
                        }
                    }

                    // Check if there is only one image or if there is only one image in the gallery and if so remove the HTML for previous/next button.
                    if (TB_TempArray.length <= 1) {
                        TB_NextHTML = "";
                        TB_PrevHTML = "";
                    }

                    var img = new Image();
                    img.src = url;

                    if (img.complete) {
                        
                        // Set options for Image viewer            
                        TB_WIDTH = 639;
                        TB_HEIGHT = 649;
                        IMG_LEFT = parseInt(((TB_WIDTH - img.width) / 2), 10);

                        jQuery('#TB_window').addClass('imagewindow');
                        jQuery("#TB_window").append("<img id='TB_Image' src='" + url + "' alt='' style='left:" + IMG_LEFT + "px;' />" + "<div id='TB_closeWindow'><img src='/media/gfx/luk_zoom.gif' id='TB_closeWindowButton' alt='St&auml;ng'></div>" + TB_PrevHTML + TB_NextHTML);

                        jQuery("#TB_closeWindowButton").click(Popcorn.Close);

                        if (!(TB_PrevURL === "")) {
                            jQuery("#TB_prev").click(function() {
                                jQuery("#TB_window").remove();
                                jQuery("body").append("<div id='TB_window'></div>");
                                Popcorn.Pop(null, TB_PrevURL, group);
                                return false;
                            });
                        }
                        else {
                            jQuery("#TB_prev").click(function() {
                                jQuery("#TB_window").remove();
                                jQuery("body").append("<div id='TB_window'></div>");
                                Popcorn.Pop(null, TB_EndURL, group);
                                return false;
                            });
                        }

                        if (!(TB_NextURL === "")) {
                            jQuery("#TB_next").click(function() {
                                jQuery("#TB_window").remove();
                                jQuery("body").append("<div id='TB_window'></div>");
                                Popcorn.Pop(null, TB_NextURL, group);
                                return false;
                            });

                        }
                        else {
                            jQuery("#TB_next").click(function() {
                                jQuery("#TB_window").remove();
                                jQuery("body").append("<div id='TB_window'></div>");
                                Popcorn.Pop(null, TB_StartURL, group);
                                return false;

                            });
                        }

                        Popcorn.PositionOverlay(false);

                        jQuery("#TB_load").remove();
                        jQuery("#TB_window").css({ display: "block" });
                    }
                    else {

                        // Here we will use an onload event for the image so that it will be positioned correctly.
                        jQuery(img).load(function() {

                            // Set options for Image viewer            
                            TB_WIDTH = 639;
                            TB_HEIGHT = 649;
                            IMG_LEFT = parseInt(((TB_WIDTH - img.width) / 2), 10);

                            jQuery('#TB_window').addClass('imagewindow');
                            jQuery("#TB_window").append("<img id='TB_Image' src='" + url + "' alt='' style='left:" + IMG_LEFT + "px;' />" + "<div id='TB_closeWindow'><img src='/media/gfx/luk_zoom.gif' id='TB_closeWindowButton' alt='St&auml;ng'></div>" + TB_PrevHTML + TB_NextHTML);

                            jQuery("#TB_closeWindowButton").click(Popcorn.Close);

                            if (!(TB_PrevURL === "")) {
                                jQuery("#TB_prev").click(function() {
                                    jQuery("#TB_window").remove();
                                    jQuery("body").append("<div id='TB_window'></div>");
                                    Popcorn.Pop(null, TB_PrevURL, group);
                                    return false;
                                });
                            }
                            else {
                                jQuery("#TB_prev").click(function() {
                                    jQuery("#TB_window").remove();
                                    jQuery("body").append("<div id='TB_window'></div>");
                                    Popcorn.Pop(null, TB_EndURL, group);
                                    return false;
                                });
                            }

                            if (!(TB_NextURL === "")) {
                                jQuery("#TB_next").click(function() {
                                    jQuery("#TB_window").remove();
                                    jQuery("body").append("<div id='TB_window'></div>");
                                    Popcorn.Pop(null, TB_NextURL, group);
                                    return false;
                                });

                            }
                            else {
                                jQuery("#TB_next").click(function() {
                                    jQuery("#TB_window").remove();
                                    jQuery("body").append("<div id='TB_window'></div>");
                                    Popcorn.Pop(null, TB_StartURL, group);
                                    return false;

                                });
                            }

                            Popcorn.PositionOverlay(false);

                            jQuery("#TB_load").remove();
                            jQuery("#TB_window").css({ display: "block" });
                        });
                    }

                    //Popcorn._imgPreLoader.src = url;
                }
                else {
                    var queryString = url.replace(/^[^\?]+\??/, '');
                    var params = Popcorn.ParseQueryString(queryString);


                    if (params['class'] == "deakningskarta") {
                        TB_WIDTH = 731;
                        TB_HEIGHT = 599;
                    }
                    else {
                        TB_WIDTH = 292;
                        TB_HEIGHT = 424;

                    }

                    ajaxContentW = (params['width'] * 1);
                    ajaxContentH = (params['height'] * 1) - 5;

                    var closeText = params['closeText'];


                    urlNoQuery = url.split('TB_');
                    jQuery("#TB_iframeContent").remove();

                    jQuery("#TB_window").addClass("iframewindow");
                    jQuery("#TB_window").addClass(params['class']);
                    jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='Popcorn.ShowIframe();' frameborder='0' scrolling='no' style='width:" + (ajaxContentW) + "px;height:" + (ajaxContentH) + "px;z-index:105;' > </iframe><div id='TB_closeIframeWindow'><span class='iframe-closeText'>" + closeText + "</span><img src='/media/gfx/luk.png' id='TB_closeWindowButton' class='iframe-close' alt='Luk'></div>");

                    jQuery("#TB_closeWindowButton").click(Popcorn.Close);

                    Popcorn.PositionOverlay(true);

                    // Our friend Safari will need some help since it won't load the Iframe correctly because it lacks interest in onload :-)
                    if (jQuery.browser.safari)
                        Popcorn.ShowIframe();
                }

            }
            else {
                // Action is set, action is basically the DIV id/class that we should fetch html from and pop.
                Popcorn._currentObject = jQuery(action);
                Popcorn._parentObject = jQuery(action).parent();
                var markup = jQuery(action);
                TB_WIDTH = jQuery(action).width();
                TB_HEIGHT = jQuery(action).height();

                jQuery(markup).show();

                jQuery('#TB_window').append(jQuery(markup));

                Popcorn.PositionOverlay(true);

                jQuery("#TB_load").remove();
                jQuery("#TB_window").css({ display: "block" });
            }
        }
        catch (ex) {
            // do nada
        }
    },

    Close: function() {
        jQuery("#TB_imageOff").unbind("click");
        jQuery("#TB_closeWindowButton").unbind("click");
        jQuery("#TB_window").fadeOut("fast", function() {
            if (Popcorn._currentObject != null) {
                Popcorn._currentObject.hide();
                Popcorn._parentObject.append(Popcorn._currentObject);
                Popcorn._currentObject = Popcorn._parentObject = null;
            }
            /* jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();  Ersattes med raden under pga problem med Flashmodulen  */
            jQuery('#TB_window,#TB_overlay,#TB_HideSelect').remove();
        });
        jQuery("#TB_load").remove();


        if (typeof document.body.style.maxHeight == "undefined") {
            jQuery("body", "html").css({ height: "auto", width: "auto" });
            jQuery("html").css("overflow", "");
        }

        document.onkeydown = "";
        document.onkeyup = "";

        return false;
    },

    ShowIframe: function() {
        jQuery("#TB_load").remove();
        jQuery("#TB_window").css({ display: "block" });
    },

    GetPageSize: function() {
        var de = document.documentElement;
        var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
        var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
        arrayPageSize = [w, h];
        return arrayPageSize;
    },

    PositionOverlay: function(PositionVertically) {
        jQuery("#TB_window").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px', height: TB_HEIGHT + 'px' });

        if (PositionVertically) {
            jQuery("#TB_window").css('top', '50%');
            if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
                jQuery("#TB_window").css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
            }
            else {
                jQuery("#TB_window").addClass('ie6VerticalPos');
            }
        }
    },

    ParseQueryString: function(query) {
        var Params = {};
        if (!query) { return Params; } // return empty object

        var Pairs = query.split(/[;&]/);
        for (var i = 0; i < Pairs.length; i++) {
            var KeyVal = Pairs[i].split('=');
            if (!KeyVal || KeyVal.length != 2) { continue; }
            var key = unescape(KeyVal[0]);
            var val = unescape(KeyVal[1]);
            val = val.replace(/\+/g, ' ');
            Params[key] = val;
        }

        return Params;
    },

    DetectIfMacFirefox: function() {
        var userAgent = navigator.userAgent.toLowerCase();
        if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
            return true;
        }

        return false;
    }
}


jQuery(document).ready(function() {
    Popcorn.Init();
});