﻿/* CODE FOR RANDOM BACKGROUND */ 
var bgPic = new Array("bg/_MG_0001.jpg","bg/_MG_0049.jpg","bg/_MG_0055.jpg","bg/_MG_0058.jpg","bg/_MG_0066.jpg","bg/_MG_0071.jpg","bg/_MG_0139.jpg","bg/_MG_0400.jpg","bg/_MG_0446.jpg","bg/_MG_0450.jpg","bg/_MG_0460.jpg","bg/_MG_0577.jpg","bg/_MG_0618.jpg","bg/_MG_9992.jpg");
function bg() {
    randomNum = Math.floor((Math.random() * bgPic.length));
    document.getElementById("bgImg").src = bgPic[randomNum];
}
// END CODE RANDOM BACKGROUND

GSJ = {
    pg: null,
    Accordion: null,
    panels: [null, 'apropos', 'titre', 'auteur', 'collection', 'nouveaute'],
    panelLoaded: [0, false, false, false, false, false],
    pageLoaded: false,
    pageScroller: null,
    collectionType: "",
    authorScroller: null,
    authorLetter: "",

    // INIT FUNCTION OF APPLICATION
    init: function() {

        var href = document.location.href;
        var actionName = href.replace(new RegExp('^.*#([^?/=&~]+)([?/=&~].*)?$'), '$1');
        var query = href.replace(new RegExp('^.*#([^?/=&~]+)[?/=&~](.*$)'), '$2');
        var vars = query.split(/\/|,|&|=|~/);

        // Check to see if Default.aspx is in the URL for ajax functionnality
        if (document.location.href.indexOf("Default.aspx") == -1) {

            if (document.location.href.indexOf('#') == -1) {
                document.location = "Default.aspx";
            } else {
                var h = document.location.href;
                h = h.replace(/(^[^#])*#(.*)$/, "$1Default.aspx#$2");
                document.location = h;
            }

        }

        // No conflict with $
        $j = jQuery.noConflict();

        // Random background
        bg();


        if (actionName == "sujet") {
            this.collectionType = "sujet";
            //actionName="collection";
        } else if (actionName == "collection") {
            this.collectionType = "collection";
        }

        if (actionName == "collection" || actionName == "sujet") {

            //alert('collections')
            index = jQuery.inArray("ID", vars)

            if (index > -1) {
                var d = document.getElementById('collections_dd');
                for (i = 0; i < d.options.length; i++) {
                    //alert("#collection/ID/"+vars[index+1]);
                    if (d.options[i].value == "#" + this.collectionType + "/ID/" + vars[index + 1]) {
                        //alert(i);
                        d.selectedIndex = i;
                    }

                }
            } else {
                var d = document.getElementById('collections_dd');
                for (i = 0; i < d.options.length; i++) {
                    //alert("#collection/ID/"+vars[index+1]);
                    if (d.options[i].value == "#" + this.collectionType + "/ID/10") {
                        //alert(i);
                        d.selectedIndex = i;
                    }

                }
            }
        }


        createDropDown();

        $j(".dropdown dt a").click(function() {
            $j(".dropdown dd ul").toggle();
        });

        $j(document).bind('click', function(e) {
            var $clicked = $j(e.target);
            if (!$clicked.parents().hasClass("dropdown"))
                $j(".dropdown dd ul").hide();
        });


        $j(".dropdown dd ul li a").click(function(e) {
            var text = $j(this).html();
            $j(".dropdown dt a").html(text);
            $j(".dropdown dd ul").hide();

            var source = $j("#collections_dd");
            source.val($j(this).find("span.value").html())
            var href = $j(this).find("span.value").html();
            //document.location="Default.aspx"+href;
            e.preventDefault();
            GSJ.onLinkClick(href);
        });


        // SEARCH FUNCTIONNALITY
        var searchTerm = $j("#q").attr("value");

        $j('#q').bind('click', function(e) {
            e.preventDefault();
            e.cancelBubble = true;
            e.stopPropagation();
            if (this.value == searchTerm) {
                this.value = "";
                $j(this).css('background-color', '#ffffff');
            }
        });
        //------------------------------------------------------------------        
        // FRANK CODE
        $j('#q').bind('keyup', function(e) {
            if (event.keyCode == '13') {
                //alert('click');
                href = 'Default.aspx#recherche/q/' + escape($j('#q').attr('value'));
                //alert(href);
                GSJ.onLinkClick(href);
            };
        });
        //------------------------------------------------------------------

        $j('#q').bind('focus', function(e) { e.stopPropagation() });
        $j('#q').bind('blur', function(e) {
            if (this.value == "") {
                this.value = searchTerm;

            }
            $j(this).css('background-color', '#cccccc');
        });
        $j('#submitSearch').bind('click', function() {
            //alert('click');
            href = 'Default.aspx#recherche/q/' + escape($j('#q').attr('value'));
            //alert(href);
            GSJ.onLinkClick(href);
        });
        // END SEARCH


        Shadowbox.init();
        this.bindLinks();


        this.Accordion = new Spry.Widget.Accordion("Accordion1");
        if (href.indexOf('#') == -1 || href.indexOf('#') == href.length - 1 || (actionName == "nouveaute" && query == href)) {
            this.Accordion.openPanel('panel5');
            this.panelLoaded[5] = true;
            this.pageLoaded = true;
        }

        this.initPage();

    },  // END INIT

    
    //bind the init
    initPage: function() {
        $j.post('Default.aspx', { "actionName": "getPages", "isAjax": "true" }, function(obj) {
            GSJ.pages = obj.toString().split(new RegExp(","));
            if (!this.pageLoaded)
                GSJ.onLinkClick(document.location.toString(), true);
        });
    },


    // bind all the links
    bindLinks: function() {
        $j('a').bind('click', function() {
            this.blur();
            GSJ.onLinkClick(this.href)
        });

        $j('.page').bind('click', function() {
            $this = $j(this);
            $j('.page').removeClass('selected');
            $this.addClass('selected');
        });
    },


    // bind the authors link
    bindAuthorLinks: function() {
        $j('.AuthorAlphaLink').bind('click', function() {

            var letter = $j(this).html();
            var letterElement = $j('#authFL_' + letter);
            if (letterElement.length > 0) {
                var letterTop = letterElement.get(0);
                var pos = letterTop.parentNode.offsetTop;
                // alert(pos);

                //alert(letter + " "+ pos);
                $j("#authorListing").scrollTop(pos);
                GSJ.authorScroller.update();
            }
            return false;

        });
    },


    // attach event and find action
    onLinkClick: function(href, dontDoAjaxCall) {

        var oldhref = document.location.toString();

        var actionName = href.replace(new RegExp('^.*#([^?/=&~]+)([?/=&~].*)?$'), '$1');
        var query = href.replace(new RegExp('^.*#([^?/=&~]+)[?/=&~](.*$)'), '$2');
        temp = query.split(/\/|,|&|=|~/);
        params = {};
        $j('.alphaLink').removeClass('selected');
        $j('.all').addClass('selected');
        if (query != href) {
            for (i = 0; i < temp.length; i += 2) {
                params[temp[i]] = temp[i + 1];
                this.authorLetter = "";
                switch (temp[i]) {
                    case 'filter':
                        if (actionName == "auteur") {
                            this.authorLetter = temp[i + 1]
                            // alert(this.authorLetter);
                        }
                        else {
                            var alinks = $j('.alphaLink');
                            alinks.removeClass('selected'); //.css('background-color','inherit').css('color','inherit');
                            $j('.alphaLink.' + actionName + '.' + temp[i + 1]).addClass('selected');
                        }
                        break;
                    default:

                        break;

                }

            }
        }

        params.actionName = actionName == ("collection" && this.collectionType == "sujet") ? "sujet" : actionName;

        if (oldhref == href) {
            oldhref = href.replace(new RegExp('(^.*#[^?/=&~]+)([?/=&~].*)?$'), '$1');
        }
        params.backLink = oldhref;


        if (actionName == href) {

            return;
        }

        // alert(href);
        if (actionName != "recherche") {
            if ((actionName == "collection" || actionName == "sujet") && (params.ID && isNaN(params.ID))) {
                //don't show link on top of page
            }
            else {
                document.location = href;
            }
        }


        if (actionName == 'recherche' || jQuery.inArray(actionName, this.pages) != -1) {

            this.Accordion.openPanel('panel1', true);
            this.ajax(params, function(text) {
                $j('#content1').show();
                GSJ.update('content1', text);

            });
        }


        if (actionName == "sujet") {
            // this.collectionType = "sujet";


            panel = 4;

            this.Accordion.openPanel("panel" + panel, true);

            if (!isNaN(params.ID)) {
                this.ajax(params, function(txt) {
                    GSJ.update('content' + panel, txt);
                });
            }
        } else
            if (jQuery.inArray(actionName, this.panels)) {


            for (i = 0; i < this.panels.length; i++) {
                if (this.panels[i] == actionName)
                    break;
            }
            panel = i;

            this.Accordion.openPanel("panel" + panel, true);

            if (actionName == "collection" && (params.ID && isNaN(params.ID))) {
                return;
            }


            if (actionName == "auteur" && this.authorLetter != "") {
                this.ajax(params, function(txt) {
                    GSJ.update('content' + panel, txt);


                });
            }
            else {
                this.ajax(params, function(txt) {
                    GSJ.update('content' + panel, txt);
                });

            }
        }
        if (actionName == "viewCart") {
            this.viewCart();
        }

    },


    // utility function to convert to string
    toString: function() {
        return 'GSJ';
    },


    //...
    getIndex: function(panel) {
        var panel = panel.substr(5);
        if (!this.panelLoaded[panel]) {
            this.ajax({ actionName: GSJ.panels[panel] }, function(response) {
                GSJ.update('content' + panel, response);
                document.location = "Default.aspx#" + GSJ.panels[panel]
                GSJ.panelLoaded[panel] = true;
            }
            );
        }

    },


    // ajax action with icon
    busy: false,
    ajax: function(obj, callback, dontShowAjaxLoading) {
        obj.isAjax = "true"
        if (this.busy)
            return;
        os = new String();
        for (key in obj) {
            os += "params." + key + " = " + obj[key] + "\n";
        }


        var ajCallback = callback
        this.busy = true;
        if (!dontShowAjaxLoading)
            $j('#ajaxLoading').show(0);

        $j.ajax({ url: "Default.aspx",
            cache: false,
            data: obj,
            type: "POST",
            dataType: "html",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                GSJ.ajaxError(textStatus);
            },
            success: function(text) {
                $j('#ajaxLoading').hide(0);
                GSJ.busy = false;
                ajCallback(text)
            }
        });
    },


    // cancel action if not working or data unreachable
    ajaxError: function(message) {
        text = "<div style=\"background-color:#ffffff;padding:25px;\"><h2>Pas Disponible</h2><p>La page demandée n'est pas disponible. Nous sommes desolé</p></div>";
        $j('#ajaxLoading').hide(0);
        bla = document.createElement("div");
        document.body.appendChild(bla);
        bla.style.visibility = "hidden";
        bla.style.position = "absolute";
        bla.style.display = "block";
        bla.innerHTML = text;
        var w = bla.offsetWidth;
        var h = bla.offsetHeight;
        Shadowbox.open({ player: 'html', content: text, overlayColor: "#ffffff", autoDimensions: true, width: w, height: h });
        this.busy = false;
    },


    // update page
    update: function(divId, content) {
        var tempdiv = document.createElement("div");
        tempdiv.style.visibility = "hidden";
        tempdiv.innerHTML = content;
        $temp = $j(tempdiv);
        var scripts = $temp.find('script');
        //alert(scripts.length);

        var target = document.getElementById(divId);
        var script = content.replace(/<script>(.*)<\/script>/g, "$2");
        var contentNoScript = content.replace(/(.*)<script>(.*)<\/script>(.*)/g, "$1$3");

        target.innerHTML = content;
        for (var i = 0; i < scripts.length; i++) {
            eval($j(scripts[i]).html());
        }
    },

    
    // add to the cart
    add2Cart: function(id) {
        params = { "actionName": "add2Cart", "ID": id };
        this.ajax(params, function(text) {
            GSJ.displayCart(text);
        });

    },
    
    
    // view the cart
    viewCart: function() {

        params = { "actionName": "viewCart" };
        this.ajax(params, function(text) {
            GSJ.displayCart(text);
        });
    },
    
    
    // display cart
    displayCart: function(text) {
        bla = document.createElement("div");
        document.body.appendChild(bla);
        bla.style.visibility = "hidden";
        bla.style.position = "absolute";
        bla.style.display = "block";
        bla.innerHTML = text;
        var w = bla.offsetWidth;
        var h = bla.offsetHeight;
        Shadowbox.open({ player: 'html', content: text, overlayColor: "#ffffff", autoDimensions: true, width: w, height: h });
    },


    // go to checkout
    checkout: function() {
        // params = {"actionName":"checkout"}
        Shadowbox.open({ player: 'iframe', content: "checkout.aspx", width: 450, height: 400 });
    },


    // empty the cart
    removeFromCart: function(id) {
        this.ajax({ actionName: "removeFromCart", ID: id }, function(text) {
            GSJ.displayCart(text);
        });
    },
    
    
    // checkout the cart
    checkoutLinkClicked: function() {
        if (confirm("Votre commande sera être envoyée par courriel et votre panier sera vidé. Voulez-vous continuer ?")) {
            this.ajax({ actionName: "clearCart" }, function(text) { });
            return true;

        } else {

            return false;
        }
    },
    
    
    // open the shadowbox
    openWindow: function(lnk) {
        ie = document.all;
        var m = window.open(lnk, "pop");
        Shadowbox.close();

    },
    
    
    // build social link pop-up
    buildSocialLinks: function() {

    if ($j('#divImgSubLinks').length)
        {
            $j('#divLinks').css('top', -$j('#divLinks').height() + 2);
            $j('#divImgSubLinks').mouseover(
			    function() {
                    $j('#divLinks').css('visibility', 'visible');
			    }
    		).mouseout(
			    function() {
			        $j('#divLinks').css('visibility', 'hidden');
			    }
		    ).css('cursor', 'pointer');
		}

    }


    // structure =
    // , functionName: function(var){}

};
