/* 
 * Tar Sands Resources by Web Molecule
 * Changes made by RAPP Edinburgh
 * Version 0.3
 * July 2011 
 * 
 * Notes:
 *  Required jQuery >= 1.4.2 (probably would would with earlier versions)
 *  Use jQuery() instead of shortcut $() to preserve functionality of any other possible libraries
 * 
 * Contents:
 *     Pagination for content of Toxic Fuels site
 *     Navigate to paginated page using anchors
 *     'Print this page' functionality
 *     Donation boxes - switch between once off and monthly
 *     Newlsetter signup
 *     Dialog for Save the Caribou game
 *     Terms and Conditions dialog
 *     Dialog for invite a friend
 *     Contact your MP dialog
 * 
 */

jQuery(document).ready(function() {
    /*
    * Variables
    */
    var baseUrl = (("https:" == document.location.protocol) ? "https://" : "http://")
					+ window.location.hostname + "/ToxicFuels/";
    var currentUrl = document.location.toString();
    var sharePageId = "156873";
    var waiting = '<img src="/upload/ToxicFuels/images/gallery/controls/loading.gif" alt="loading" width="32" height="32" />';
    var blankThumb = '<img class="blankThumb" width="47" height="36" src="/upload/ToxicFuels/images/thumbnail-blank.png" alt="">';

    /* 
     * Dynamic host variables
     */
    if (window.location.hostname == "www.co-operative.coop" || window.location.hostname == "co-operative.coop") {
    	//live server, most settings set above
    	
    } else if (window.location.hostname == "coop30.ultimedia.co.uk") {
    	//testing server
    	sharePageId = "145698";
        baseUrl = (("https:" == document.location.protocol) ? "https://" : "http://")
		+  "coop30.ultimedia.co.uk/Toxic-Fuels/";
    } else {
    	//localhost
    	sharePageId = "145698";
        baseUrl = (("https:" == document.location.protocol) ? "https://" : "http://")
		+  "coop30.ultimedia.co.uk/Toxic-Fuels/";
    }
    /* 
     * Browser fixes
     */
    if (jQuery.browser.opera) {
    	jQuery("body").addClass("opera");
    }
    /*
    * General functions 
    */
    function isValidEmail(str) {
        // These comments use the following terms from RFC2822:
        // local-part, domain, domain-literal and dot-atom.
        // Does the address contain a local-part followed an @ followed by a domain?
        // Note the use of lastIndexOf to find the last @ in the address
        // since a valid email address may have a quoted @ in the local-part.
        // Does the domain name have at least two parts, i.e. at least one dot,
        // after the @? If not, is it a domain-literal?
        // This will accept some invalid email addresses
        // BUT it doesn't reject valid ones. 
        var atSym = str.lastIndexOf("@");
        if (atSym < 1) { return false; } // no local-part
        if (atSym == str.length - 1) { return false; } // no domain
        if (atSym > 64) { return false; } // there may only be 64 octets in the local-part
        if (str.length - atSym > 255) { return false; } // there may only be 255 octets in the domain

        // Is the domain plausible?
        var lastDot = str.lastIndexOf(".");
        // Check if it is a dot-atom such as example.com
        if (lastDot > atSym + 1 && lastDot < str.length - 1) { return true; }
        //  Check if could be a domain-literal.
        if (str.charAt(atSym + 1) == '[' && str.charAt(str.length - 1) == ']') { return true; }
        return false;
    }

    /*
    * Extend jQuery to center divs
    */
    jQuery.fn.center = function() {
        var top = (jQuery(window).height() - this.height()) / 2 + jQuery(window).scrollTop();
        var left = (jQuery(window).width() - this.width()) / 2 + jQuery(window).scrollLeft();

        if (top < 0) { top = 0; };
        if (left < 0) { left = 0; };
        //if(jQuery.browser.msie) { left = left/2; }

        this.css("position", "absolute");
        this.css("top", top + "px");
        this.css("left", left + "px");
        return this;
    }

    /*
    * is_array function 
    */
    function is_array(input) {
        return typeof (input) == 'object' && (input instanceof Array);
    }

    /*
    * Pagination
    */
    jQuery("#contentMiddle a").live("click", function(event) {
        //left click only
        if (!event.which || event.which == 1) {
            //which page is being clicked?
            var page = jQuery(this).attr("title").replace(" ", "-");
            var selectedLink = this;
            //check if this is a link with title attr set
            if (this.title.match("page") == "page") {
                selectedLink = "#bulletNav li:eq(" + (this.title.charAt(5)) + ") a";
                //alert(selectedLink);
            }

            //if this is prev/next button, figure out which page is selected
            //alert(page);
            if (page == 'previous') {
                var currPage = parseInt(jQuery("#bulletNav a.selected").attr("title").replace(" ", "-").charAt(5));
                page = "page-" + (currPage - 1);
                selectedLink = "#bulletNav li:eq(" + (currPage - 1) + ") a";

            }
            if (page == 'next') {
                var currPage = parseInt(jQuery("#bulletNav a.selected").attr("title").replace(" ", "-").charAt(5));
                page = "page-" + (currPage + 1);
                selectedLink = "#bulletNav li:eq(" + (currPage + 1) + ") a";
            }

            //only if the new page can be found
            if (page.length > 0 && jQuery("#" + page).length) {
                //prevent default behaviour
                event.preventDefault();
                //remove selected class from all links
                jQuery("#bulletNav a").removeClass("selected");
                //add selected to clicked link
                jQuery(selectedLink).addClass("selected");

                //change url
                var newUrl = currentUrl;
                if (currentUrl.match('#')) {
                    //existing anchor, replace
                    newUrl = currentUrl.split('#')[0] + "#" + page;
                } else {
                    //no anchor, add
                    newUrl += "#" + page;
                }
                //set url
                document.location = newUrl;

                //hide existing pages
                jQuery(".page").hide();
                //show correct page
                jQuery("#" + page).fadeIn();
            }
        }
    });

    /*
    * Navigate to paginated page using anchors
    */
    var currentUrlNoHash = currentUrl;
    if (currentUrl.match('#')) {
        // the URL contains an anchor
        // click the navigation item corresponding to the anchor
        var page = currentUrl.split('#')[1];
        currentUrlNoHash = currentUrl.split('#')[0]

        // only if the new page can be found
        if (page.length > 0 && jQuery("#" + page).length) {
            page = page.replace("-", " ");
            jQuery("#bulletNav a[title=" + page + "]").click();
        }
    }
    //add meaningful anchor to urls
    jQuery("#bulletNav a")
	.each(function(item) {
	    jQuery(this).attr("href", currentUrlNoHash + "#" + jQuery(this).attr("title").replace(" ", "-"));
	});

    /*
    * 'Print this page' functionality
    */
    if (jQuery("#footerNav > li.first > a").length) {
        jQuery("#footerNav > li.first > a").live("click", function(event) {
            //left click only
            if (!event.which || event.which == 1) {
                event.preventDefault();
                //print page
                window.print();
                return false;
            }
        });
    }


    /*
    * Background changer
    * 	Loop through with fade effect
    * 	Hover over thumbnail effect
    * 	Hide thumbnail of current background
    */
    //only do all this if we have thumbnails
    if (jQuery("#thumbnails > ul > li").length) {
        //Loop through with fade effect
        var imageCount = jQuery("#thumbnails > ul > li").length;
        var prevImage = -1;
        var currImage = 1;
        var imageWaiting = false;
        var backgroundChanger = false;

        function setBackground() {
            //switch thumbnails
            jQuery("#thumbnails li").removeClass("selected");
            jQuery("#thumbnails .blankThumb").remove();

            jQuery("#thumbnails li:eq(" + prevImage + ")")
            	.addClass("selected")
            	.contents("a").contents("img").after(blankThumb);
            //jQuery("#thumbnails li:eq("+prevImage+")").fadeIn("slow");
            //jQuery("#thumbnails li:eq("+currImage+")").hide();

            //which background to display?
            var background = (currImage == 0 ? imageCount : currImage);

            //switch background
            jQuery("#bgFader").fadeOut("slow", function() {
                jQuery("#bgFader").removeClass().addClass("bg" + background).fadeIn("slow");
            });
        }

        function loopBackgrounds() {

            if (!imageWaiting) {
                imageWaiting = true;
                backgroundChanger = setInterval(function() {
                    imageWaiting = false;
                    prevImage = currImage;
                    currImage = ++currImage % (imageCount);
                    setBackground();

                }, 5000); //time in milliseconds
            } else { alert('waiting'); }
        }
        //loopBackgrounds();
        //add blank thumbnail to selected thumbnail

        jQuery("#thumbnails li.selected > a > img").after(blankThumb);

        //thumbnail click
        jQuery("#thumbnails > ul > li > a").click(function(event) {
            //left click only
            if (!event.which || event.which == 1) {
                event.preventDefault();
                //stop the looping
                clearInterval(backgroundChanger);
                imageWaiting = false;
                //set image to display
                currImage = jQuery(this).parent().index() + 1;
                prevImage = currImage - 1;
                //set background
                setBackground();
                //continue looping?
                //loopBackgrounds();
            }
        });

        //Hover effect
        jQuery("#thumbnails > ul > li > a").hover(
			function() {
			    //mouseover
			    jQuery(this).parent().addClass("hover");
			},
			function() {
			    //mouseout
			    jQuery(this).parent().removeClass("hover");
			}
		);
    }

    /*
    * Donation boxes - switch between once off and monthly
    */
    jQuery("a.monthlyDonationText").click(function(event) {
        //left click only
        if (!event.which || event.which == 1) {
            event.preventDefault();
            //determine if once off or monthly
            if (jQuery(this).hasClass("monthly")) {
                //monthly is set, lets change to once off
                jQuery("#donateBox").fadeOut(function() {
                    //change name of amount box
                    jQuery("#donateAmount").attr("name", "amount");

                    //change command value
                    jQuery("#cmd").val("_xclick");

                    //change link text and remove monthly class
                    jQuery("a.monthlyDonationText")
						.attr("title", "Send monthly donation")
						.html("Send monthly donation")
						.removeClass("monthly");
                }).fadeIn();
            } else {
                //once off is set, lets change to monthly
                jQuery("#donateBox").fadeOut(function() {
                    //change name of amount box	
                    jQuery("#donateAmount").attr("name", "a3");

                    //change command value
                    jQuery("#cmd").val("_xclick-subscriptions");

                    //change link text and add monthly class
                    jQuery("a.monthlyDonationText")
						.attr("title", "Send once-off donation")
						.html("Send one-off donation")
						.addClass("monthly");
                }).fadeIn();
            }
        }
    });
    

    function dialogBeforeShow() {
    	//we are about to show 
    	
        //close existing dialogs
        jQuery(".dialog").fadeOut();
        
        //hide videos
        jQuery("object:visible, embed:visible").hide();
    }
    
    function dialogAfterHide() {
    	//we have just hidden a dialog
        
        //show hidden videos
        jQuery("object:hidden, embed:hidden").show();  
    }

    /*
    * Basic dialog - Save the Caribou
    */
    if (jQuery("#caribou-container").length) {

        //draggable
        jQuery("#caribou-container").draggable({ handle: ".heading > h1" });
        jQuery("#caribou-container .heading > h1").css("cursor", "move");

        //Open
        jQuery(".popup-caribou").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                dialogBeforeShow();
                //show dialog
                jQuery("#caribou-container").center().fadeIn();
                //then show flash
                jQuery("#widgetbox_widget").show();
                return false;
            }
        });

        //Close
        jQuery("#caribou-container .close > a").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                //first hide flash
                jQuery("#widgetbox_widget").hide();
                jQuery("#caribou-container").fadeOut();
                dialogAfterHide();
                return false;
            }
        });
    }

    /*
    * Terms and Conditions dialog
    */
    if (jQuery("#terms-container").length) {

        //draggable
        jQuery("#terms-container").draggable({ handle: ".heading > h1" });
        jQuery("#terms-container .heading > h1").css("cursor", "move");

        //Open
        jQuery(".popup-terms").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                dialogBeforeShow();
                //show dialog
                jQuery("#terms-container").center().fadeIn();
                return false;
            }
        });

        //Close
        jQuery("#terms-container .close > a").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                jQuery("#terms-container").fadeOut();
                dialogAfterHide();
                return false;
            }
        });
    }
	
	/*
    * Video overlay
    */
    if (jQuery("#video-container").length) {

        //draggable
        jQuery("#video-container").draggable({ handle: ".heading > h1" });
        jQuery("#video-container .heading > h1").css("cursor", "move");

        //Open
        jQuery(".popup-video").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                dialogBeforeShow();
				jQuery("#video-area").html('<object style="height: 390px; width: 640px"><param name="movie" value="http://www.youtube.com/v/VdWo0n75P58?version=3"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed src="http://www.youtube.com/v/VdWo0n75P58?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="390"></object>');
                //show dialog
                jQuery("#video-container").center().fadeIn();
                return false;
            }
        });

        //Close
        jQuery("#video-container .close > a").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                jQuery("#video-container").fadeOut();
				jQuery("#video-area").html(' ');
                dialogAfterHide();
                return false;
            }
        });
    }

    /*
    * Contact your MP dialog
    */
    if (jQuery("#contactmp-container").length) {

        //draggable
        jQuery("#contactmp-container").draggable({ handle: ".heading > h1" });
        jQuery("#contactmp-container .heading > h1").css("cursor", "move");

        //Open
        jQuery(".contactmp-link").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                dialogBeforeShow();
                //show dialog
                var url = baseUrl + "Forms/Contact-your-MP/";
                var iframe = '<iframe class="hidden" frameBorder="0" id="frame-mp" name="frame-mp" src="' + url + '"></iframe>';
                var wait = '<div id="contactmp-wait" style="margin-top: 200px; text-align: center; height: 235px;">' + waiting + '</div>';
                jQuery("#contactmp-form-area").html(wait);
                jQuery("#contactmp-wait").after(iframe);
                jQuery("#contactmp-container").center().fadeIn();
                //show iframe when ready
                jQuery("#frame-mp").load(function(e) {
                    //iframe has loaded
                    jQuery(this).fadeIn();
                    jQuery("#contactmp-wait").remove();
                });
                return false;
            }
        });

        //Close
        jQuery("#contactmp-container .close > a").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                jQuery("#contactmp-container").fadeOut();
                dialogAfterHide();
                return false;
            }
        });
    }

    /*
    * Newsletter signup
    */
    function newslettterDisplayResponse(message) {
        if (!message || message == "") {
            message = "Please try again";
        }

        jQuery("#newsletterResponse")
			.html(message)
			.fadeIn()
			.delay(2500)
			.fadeOut();
    }

    //form submit
    jQuery("#banner > form").submit(function(event) {
        event.preventDefault();

        //check if response div has been created
        if (!jQuery("#newsletterResponse").length) {
            var html = '<div id="newsletterResponse"></div>';
            jQuery("#banner > form #email").after(html);
        }

        //simple validation
        if (!isValidEmail(jQuery("#banner > form #email").val())) {
            newslettterDisplayResponse("Please enter a valid email address");
            return false;
        }

        //ajax post data
        jQuery.ajax({
            type: "POST",
            url: baseUrl + "Forms/Newsletter-Signup",
            beforeSend: function(xhr) {
	            xhr.setRequestHeader("X-MicrosoftAjax", "Delta=true");
            },
            dataType: "json",
            data: {
                ctl00$Content$FormControl$FormControl$email_address: jQuery("#banner > form #email").val(),
                ctl00$Content$FormControl$FormControl$ctl00: "Submit",
                __EVENTTARGET: ""
            },
            success: function(response) {
                //success?
                newslettterDisplayResponse("Thank you");
            },
            error: function(response) {
                //console.log(response); 
                if (response.statusText == 'OK') {
                    //parse text response
                    var text = response.responseText;
                    //first chunk (separated by pipe | ) is content length, second chunk is response word, third is response code
                    var pos1 = text.indexOf("|") + 1;
                    var pos2 = text.indexOf("|", pos1);
                    var responseCode = text.substring(pos1, pos2);
                    if (responseCode == "pageRedirect") {
                        //success
                        newslettterDisplayResponse("Thank you");
                    } else {
                        //error
                        newslettterDisplayResponse("Please ensure the address you entered is a valid email address");
                    }
                } else {
                    //error
                    newslettterDisplayResponse("An error occured, please try again later");
                }
            }
        });
        return false;
    });

    //focus on newsletter input
    jQuery("#banner > form #email").focusin(function(event) {
        if (jQuery(this).val() == this.defaultValue) {
            jQuery(this).val("");
        }
    });
    //focus off newsletter input
    jQuery("#banner > form #email").focusout(function(event) {
        if (jQuery(this).val() == "") {
            jQuery(this).val(this.defaultValue);
        }
    });

    /*
    * Invite dialog
    */
    if (jQuery("#invite-container").length) {
    	//load page to gerenate coockie, etc.
        var url = (baseUrl + "Forms/Send-to-a-Friend?pageRef=" + sharePageId);
        jQuery.post(url, function(data) {
        	  //alert('Load was performed.');
    	});

        //functions for success and failure
        function inviteSuccess(response) {
            //success
            var message = 'Thank you for inviting your friends. Feel free to invite more!';
            if (response.message) {
                message = response.message;
            }
            jQuery("#invite-container .message").html(message);
            //clear friends emails
            jQuery("#friendsemails").val("");
        }

        function inviteError(response) {
            var message = 'There were errors while processing your invite. Please try again later.';
            if (response && response.message) {
                message = response.message;
            }
            jQuery("#invite-container .message").html(message);
            //set error messages
            if (response && response.errors) {
                for (var i in response.errors) {
                    jQuery("#" + i).prev(".error-msg").html(response.errors[i]);
                }
            }
        }

        function PaginationFixHide(pageid) {

            //hideMe
            document.getElementById('rightContent').style.visibility = 'hidden';
            document.getElementById(pageid).style.width = "629px";
        }

        //draggable
        jQuery("#invite-container").draggable({ handle: ".heading > h1" });
        jQuery("#invite-container .heading > h1").css("cursor", "move");

        //Open
        jQuery(".invite-link").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                dialogBeforeShow();
                //show dialog
                jQuery("#invite-container").center().fadeIn();
                return false;
            }
        });

        //Close
        jQuery("#invite-container .close > a").live("click", function(event) {
            if (!event.which || event.which == 1) {
                event.preventDefault();
                jQuery("#invite-container").fadeOut();
                dialogAfterHide();
                return false;
            }
        });


        //Submit
        jQuery("#invite-form").submit(function(event) {
            event.preventDefault();

            //simple validation
            var valid = true;
            jQuery("#yourname").prev(".error-msg").html("");
            if (!jQuery("#yourname").val().length) {
                jQuery("#yourname").prev(".error-msg").html("Your name is required.");
                valid = false;
            }
            jQuery("#youremail").prev(".error-msg").html("");
            if (!jQuery("#youremail").val().length) {
                jQuery("#youremail").prev(".error-msg").html("Your email is required.");
                valid = false;
            }
            jQuery("#friendsemails").prev(".error-msg").html("");
            if (!jQuery("#friendsemails").val().length) {
                jQuery("#friendsemails").prev(".error-msg").html("Your friends' email is required.");
                valid = false;
            }

            if (!valid) { return false; }

            //show waiting graphic
            jQuery("#invite-container .message").html(waiting);

            //serialize data
            url = (baseUrl + "Forms/Send-to-a-Friend?pageRef=" + sharePageId);
            //alert(url);

            //ajax post data
            jQuery.ajax({
                type: "POST",
                url: url,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("X-MicrosoftAjax", "Delta=true");
                },
                dataType: "json",
                data: {
                    yourname: jQuery("#yourname").val(),
                    youremail: jQuery("#youremail").val(),
                    friendsemail: jQuery("#friendsemails").val(),
                    yourmessagebody: jQuery("#message").val(),
                    btnSend: "send",
                    __EVENTTARGET: ""
                },
                success: function(response) {
                    //console.log(response);
                    if (response && response.result) {
                        //success
                        inviteSuccess(response);
                    }
                    else {
                        //error
                        inviteError(response);
                    }
                },
                error: function(response) {
                    //alert('err');
                    //console.log(response); 
                    if (response.statusText == 'OK') {
                        //parse text response
                        var text = response.responseText;
                        //first chunk (separated by pipe | ) is content length, second chunk is response word, third is response code
                        var pos1 = text.indexOf("|") + 1;
                        var pos2 = text.indexOf("|", pos1);
                        var responseCode = text.substring(pos1, pos2);
                        if (responseCode == "pageRedirect") {
                            //success
                            inviteSuccess(response);
                        } else {
                            //error
                            inviteError(response);
                        }
                    } else {
                        //error
                        inviteError(response);
                    }
                }
            });
            return false;
        });
    }
});

