/*
 * Javascript/JQuery - Main functions
 * @author: valerie hanesse @ readingroom.com
 * @date: 26.11.2009
 * 
 * ************************************************************/
jQuery(document).ready(function() {

    //apply a js class on te body
    var body = jQuery("body");
    if (!body.hasClass("js")) { body.addClass("js") };

    //external links
    var externalLinks = jQuery(".external");
    if (externalLinks.parents("#partners").size() != 1) {
        externalLinks.append(" <span>(external link)</span>");
    }
    externalLinks.click(function() { window.open(jQuery(this).attr("href")); return false; });
    externalLinks.keypress(function(e) { window.open(jQuery(this).attr("href")); return false; });

    //dob - checker form
    jQuery(".dob").focus(function() {
        if (jQuery(this).val() == "dd") { jQuery(this).val(""); }
    });
    jQuery(".dob").blur(function() {
        if (jQuery(this).val() == "") { jQuery(this).val("dd") }
    });
    jQuery(".dobmonth").focus(function() {
        if (jQuery(this).val() == "mm") { jQuery(this).val(""); }
    });
    jQuery(".dobmonth").blur(function() {
        if (jQuery(this).val() == "") { jQuery(this).val("mm") }
    });
    jQuery(".dobyear").focus(function() {
        if (jQuery(this).val() == "yyyy") { jQuery(this).val(""); }
    });
    jQuery(".dobyear").blur(function() {
        if (jQuery(this).val() == "") { jQuery(this).val("yyyy") }
    });

    //popup
    var popupStatus = 0;
    function centerPopup(popup, top) {
        //request data for centering
        var height = popup.css("height");
        //opera will have height set up only when showing the popup, so the propoerty would be equal to 0px
        if (height == "0px") { height = "384px"; }
        var lh = height.length;
        height = height.substr(0, lh - 2);
        var width = popup.css("width");
        //opera will have width set up only when showing the popup, so the propoerty would be equal to 0px
        if (width == "0px") { width = "408px"; }
        var lw = width.length;
        width = width.substr(0, lw - 2);
        var windowWidth = jQuery(window).width();
        var windowHeight = jQuery(window).height();
        //centering
        //popup.css({"position": "absolute","top": (windowHeight-384)/2,"left": (windowWidth-408)/2});
        if (ua != "IE 6") {// variable set via conditionals in the master, "" if no IE 6
            popup.css({ "top": (windowHeight - height) / 2, "left": (windowWidth - width) / 2 });
        } else {
            if ((jQuery(document).height() - top - 100) > height) {
                popup.css({ "top": top, "left": (windowWidth - width) / 2 });
            } else {
                popup.css({ "top": (top - height), "left": (windowWidth - width) / 2 });
            }
        }
    }
    function disablePopup(popup, popupbg) {
        /*alert("ca marche");*/
        if (popupStatus == 1) {
            //disables popup only if it is enabled
            popup.fadeOut("slow");
            popupbg.fadeOut("slow");
            jQuery("#background-popup div.popup-content").remove();
            popupStatus = 0;
        }
    }
    var clicksList = jQuery(".popup .click");
    if (clicksList.size() >= 0) {//if there is any calls to popup on the page
        //add bg section
        var popupbg = jQuery("body").append("<div id=\"background-popup\" class=\"pngbg\"></div>");
        //add a close button per popup content that will close the popup
        //var closeElts = jQuery("<a class=\"popup-close\">x</a>").prependTo(clicksList.next("div.popup-content"));
        var closeElts = jQuery("<a class=\"popup-close\">x</a>").prependTo("div.popup-content");

        clicksList.next("div.popup-content").each(function(i) {
            var info = jQuery(this).children("dl.info");
            if (info.size() > 0) {
                var startDate, startTime, endTime = "";
                var schedule = false;
                if (info.children("dd.start-date").html() != null) { startDate = info.children("dd.start-date").html(); schedule = true; }
                if (info.children("dd.start-time").html() != null) { startTime = info.children("dd.start-time").html(); schedule = true; }
                if (info.children("dd.end-time").html() != null) { endTime = " - " + info.children("dd.end-time").html(); schedule = true; }
                if (schedule) { jQuery("<p class=\"info bold\">" + startDate + ", " + startTime + endTime + "</p>").insertBefore(jQuery(this)); }
                if (info.children("dd.address1").html() != null) {
                    jQuery("<p class=\"info\">" + info.children("dd.address1").html() + "</p>").insertBefore(jQuery(this));
                }
            }
        });
        closeElts.click(function() {
            disablePopup(jQuery("div.popup-content"), jQuery("#background-popup"));
        });
        clicksList.click(function() {
            popupStatus = 1;
            var popupContent = jQuery(this).siblings("div.popup-content").clone(true);
            if (jQuery(this).is('span')) {
                var popupContent = jQuery(this).parent('p').siblings("div.popup-content").clone(true);
            }
            var h4Elts = popupContent.children("h4");
            h4Elts.replaceWith('<p class="popup-subtitle">' + h4Elts.html() + '</p>');
            popupContent.prepend("<p class=\"popup-title\">" + jQuery(this).html() + "</p>");
            if (popupContent.size() >= 0) {
                var bg = jQuery("#background-popup");
                bg.append(popupContent);
                centerPopup(popupContent, jQuery(this).offset().top);
                bg.fadeIn("slow");
                popupContent.fadeIn("slow");
            }
        });

    }

    //------- LISTING AND MORE TOOL
    var listings = jQuery(".listing ul.items");
    var nbListings = listings.size();
    if (nbListings > 0 && jQuery("body.partners").size() == 0) {
        //alert(nbListings);
        listings.each(function(i) {
            var liChildren = jQuery(this).children("li");
            var lg = liChildren.size();
            //alert(lg);
            if (lg >= 4) {
                for (j = 3; j < lg; j++) {
                    var _li = liChildren.get(j);
                    jQuery(_li).toggleClass("hidden");
                }
                if (jQuery(this).hasClass("centres")) {
                    var seeAllElts = $('<p class="see-all add"><span>Show all centres</span></p>').insertAfter(this);
                }
                else {
                    var seeAllElts = $('<p class="see-all add"><span>Show all events</span></p>').insertAfter(this);
                }

                seeAllElts.click(function() {
                    var ulElt = jQuery(this).prev("ul.items");
                    var liElts = ulElt.children("li");
                    var nb = liElts.size();
                    if (nb >= 4) {
                        for (k = 3; k < lg; k++) {
                            var _liElt = liElts.get(k);
                            jQuery(_liElt).toggleClass("hidden");
                        }
                    }
                    //alert(jQuery(this).text());
                    if (jQuery(this).text() == "Show all centres") {
                        jQuery(this).html("<span>Do not show all centres</span>");
                        jQuery(this).removeClass("add");
                        jQuery(this).addClass("minus");
                    }
                    else if (jQuery(this).text() == "Do not show all centres") {
                        jQuery(this).html("<span>Show all centres</span>");
                        jQuery(this).removeClass("minus");
                        jQuery(this).addClass("add");
                    }
                    else if (jQuery(this).text() == "Show all events") {
                        jQuery(this).html("<span>Do not show all events</span>");
                        jQuery(this).removeClass("add");
                        jQuery(this).addClass("minus");
                    }
                    else {
                        jQuery(this).html("<span>Show all events</span>");
                        jQuery(this).removeClass("minus");
                        jQuery(this).addClass("add");
                    }
                });
            }
        });

    }

    //place the h1 in the content text area
    if (jQuery("#content-input")) {
        var header = jQuery("h1:first")
        var n = header.size();
        if (n == 1) {
            var str = header.text()
            jQuery("#content-input").prepend('<div class="header">' + str + '</div>');
        }
    }

    //fix choose area hover for the sake of ie6
    jQuery(".chooseArea li").hover(
		function() { jQuery(this).addClass('hover') },
		function() { jQuery(this).removeClass('hover') }
	);

    //enhance choose area for better tabbing browser wide
    jQuery(".chooseArea li a").focus(
		function() { jQuery(".chooseArea li").addClass('hover') }
	);
    jQuery(".chooseArea li a").blur(
		function() { jQuery(".chooseArea li").removeClass('hover') }
	);



    /* ----- INLINE VALIDATION ENHANCEMENT FOR ORDER FORM----- */

    // ----- PART ONE: FOR REQUIRED FIELDS ----- //
    jQuery('.orderForm label.required').siblings('input').blur(function() {
        currentField = jQuery(this);
        if (currentField.attr('class') !== 'mobileTxt') {

            // if the current field is empty and doesn't alredy have validation: add valiation
            if (currentField.val() == "") {
                if (currentField.attr('class') !== 'not-valid') {
                    currentField.addClass('not-valid');
                    currentField.after('<span class="validation"><span class="not-valid">not valid</span> This field is mandatory</span>')
                }
            }

            // if the current field is now correct: remove validation
            else {
                currentField.removeClass('not-valid');
                currentField.siblings('.validation').remove();
            }

        }
    });

    // ----- PART TWO: FOR THE PHONE FIELD ----- //
    var mobField = jQuery('.orderForm .mobileTxt');
    var numbersOnly = /^[0-9]+$/;

    // mobile validation msg if validation does not already exist
    function mobMsg() {
        if (mobField.attr('class') !== 'not-valid') {
            mobField.addClass('not-valid');
            mobField.after('<span class="validation"><span class="not-valid">not valid</span><span class="white-bubble"><span class="message"><span class="scroll"><span>Sorry, UK numbers only.</span></span></span></span></span>')
        }
    };

    mobField.blur(function() {
        // remove spaces
        var mobileNum = mobField.val();
        mobField.val(mobileNum.replace(" ", ""));
        // if the field contains only numbers...
        if (mobField.val().match(numbersOnly)) {
            // ...and if the length is exactly 11 numbers: remove validation
            if (mobField.val().length == 11) {
                mobField.removeClass('not-valid');
                mobField.siblings('.validation').remove();
            }
            // ...or if the length is not exactly 11 numbers: add validation
            else { mobMsg(); }
        }
        // if the field does not only contain numbers and doesn't already have validation add validation
        else { mobMsg(); }
    });

    /*DATE PICKER*/
    //hook a picker on each .datepicker class elt
    jQuery(".datepicker").each(function() {
        //hook and set up the date format: dd/mm/yyyy 
        jQuery(this).datepicker({ dateFormat: 'dd/mm/yy' });
        var initialDate = jQuery(this).val();
        if ((initialDate != "") && (/^\d{2}\/\d{2}\/\d{4}$/.test(initialDate))) {//if there is a date defined
            var tabValues = initialDate.split("/");
            var d = parseInt(tabValues[0]);
            var m = parseInt(tabValues[1]);
            var y = parseInt(tabValues[2]);
            jQuery(this).datepicker('setDate', new Date(y, m - 1, d));
        }
    });

    /*BUGS*/
    /* disabled attribute IE 6/7 */
    if (ua == "IE 6" || ua == "IE 7") {
        jQuery("option[disabled]").css({ "color": "#555" });
        jQuery("select").change(function() {
            if (this.options[this.selectedIndex].disabled) {
                this.selectedIndex = 0;
            }
        });
    }

});
