/**
 * @id allUsers.js
 * @author tim.beadle@iop.org
 * @version $Id: allUsers.js,v 1.76 2010/12/03 15:21:47 czb Exp $
 */
 
/*jslint browser: true */
/*extern jQuery, $, cws, cwsConfig, utils, pageTracker, Shadowbox */

if (typeof(Shadowbox) != "undefined") {
	Shadowbox.loadSkin('classic',cwsConfig.contextPath+'js/lib/shadowbox/skin/');
	Shadowbox.loadLanguage('en',cwsConfig.contextPath+'js/lib/shadowbox/lang/');
	Shadowbox.loadPlayer(['flv'],cwsConfig.contextPath+'js/lib/shadowbox/player/');
}

/**
 * Extend jQuery with a check and uncheck function for checkboxes
 * @extends jquery
 */
$.fn.extend({
    check: function(){
        return this.each(function(){
            this.checked = true;
        });
    },
    uncheck: function(){
        return this.each(function(){
            this.checked = false;
        });
    }
});

var AllUsers = {

	comments : {
		maxLength : 0
	},

    /**
     * Init method - attached to the document.ready event
     * @id AllUsers.init
     */
    init: function(){
    	
    	if (typeof(Shadowbox) != "undefined" && $("a[rel^=shadowbox]").size() > 0) {
    		var options = {
    			flvPlayer: cwsConfig.contextPath + 'multimedia/mediaplayer-45.swf',
    			loadingImage: cwsConfig.contextPath + 'icons/platform/loadingAnimation.gif',
    			overlayBgImage: cwsConfig.contextPath + 'icons/platform/overlay-85.png',
    			autoplayMovies: true
    		};
    		Shadowbox.init(options);
    		
    		
    		var videoLinkSelector = "div.videos a[href^=http], div.videos a[href^=/]";
    		$(videoLinkSelector).each(function() {
				var pathArray = $(this).attr("href").split("/");
				var videoFile = pathArray.pop();
				var videoChannel = pathArray.pop();
				if (videoFile.indexOf(';') > 0){
					videoFile = videoFile.split(";")[0];
				}	
				$(this).attr("href", cwsConfig.videoBaseUrl + videoChannel + '/' + videoFile);
			});
			$(videoLinkSelector).click(function(){
				AllUsers.trackPageview("/video/" + this.href);
			});
    		Shadowbox.setup($(videoLinkSelector));
    	}
    	
    	AllUsers.attachEvents();
    	AllUsers.initGalleria();
		
		// AllUsers.addDateWidgets(); // datePicker is nolonger in use - can this go now? - czb 050809
        
        // Restrict the width of article elements' titles to the width of
        // the elements themselves.
        // Different behaviour for IE than other browsers
        if ($.browser.msie) {
            AllUsers.restrictArticleElementWidth();
        }
        else {
            $(".articleElement img").load(AllUsers.restrictArticleElementWidth);
        }
        // Enchanced Institute login (tabs between IOP and CWS logins)
        if ($("#instituteLogin").size() > 0) {
            AllUsers.enhanceInstituteLogin();
        }
        // Subject filter navigation expand/collapse
        $("#subjectNav h3").addClass('collapso');
        
        // Indicate the remaining characters in textareas
        // Create a container for the "characters remaining" text 
        $(".showCharsRemaining").parent().find("label").append("&nbsp;<em></em>");
        
        /*
         * For each form element with class .showCharsRemaining,
         * indicate the characters remaining.
         */ 
        $(".showCharsRemaining").each(function(){
            /*
             * If it's a "stealth-mode" length indicator, hide the "max length" 
             * note
             */
            if ($(this).is('.stealth')) {
                $(this).parent().find('span').hide();
            }
            // Do the length indication onload...
            AllUsers.showCharsRemaining(this);
            // ...and attach to the keyup event 
            $(this).keyup(function(){
                AllUsers.showCharsRemaining(this);
            });
        });
        
		// Provides Google Analytics Event Tracking by simply supplying a class of 'gaRecord' to an 'a href' tag
        // Parameters: category,action and label
		// CZB - 16Th Feb 2009		
		$("a.gaRecord").click(function(event){
			var url = this.href;
			var asset = url.split("/");
			var l = asset.length-1;
			var filename = asset[l];
			AllUsers.trackEvent('document','download',filename);
		});
          
        // Counts impressions of CP, KS via Google Analytics
		// Parameters: category,action and label
        $("a.companyLogo").each(function(event){
        	// var url = this.href;      	
        	var asset = this.href.split("/");
        	var companyCode = this.id;
        	if (!companyCode) { companyCode = asset[5]; }
        	var data = location.href + " : " + companyCode + " : " + this.href;
        	AllUsers.trackEvent('logo','impression', data);        	
        });
        
        // Counts click-throughs of CP, KS logos and links via Google Analytics
		// Parameters: category,action and label
        $("a.companyLogo").click(function(event){     	
        	var asset = this.href.split("/");
        	var companyCode = this.id;
        	if (!companyCode) { companyCode = asset[5]; }       	
        	var data = location.href + " : " + companyCode + " : " + this.href;
        	AllUsers.trackEvent('logo','click', data);
        }); 
        
        $("a.companyLink").click(function(event){     	
        	var asset = this.href.split("/");
        	var companyCode = this.id;
        	if (!companyCode) { companyCode = asset[5]; }
        	var data = location.href + " : " + companyCode + " : " + this.href;
        	AllUsers.trackEvent('companyLink','click', data);
        }); 
               
        $("a.companyLink").each(function(event){     	
        	var asset = this.href.split("/");
        	var companyCode = this.id;
        	if (!companyCode) { companyCode = asset[5]; }
        	var data = location.href + " : " + companyCode + " : " + this.href;
        	AllUsers.trackEvent('companyLink','impression', data);
        }); 
        
        $("a.share").click(function(event){	
        	var data = location.href + " : " + this.href;
        	AllUsers.trackEvent('share','click', data);
        }); 
        
        // Count external link requests
        // Parameters: category,action and label
        $("a.click").click(function(event){
        	AllUsers.trackEvent('link','click', this.href);
        });      
        
        /* end of analytics */
        
        /* Comment moderation - select/toggle all checkboxes - czb 03/12/2010 */
        $("#selectAll").click(function() {
        	var checked_status = this.checked;
			$("input[@name=commentId]").each(function()
			{
				this.checked = checked_status;				
			});
			$("div.toggleText").toggle();
        });        
        
        // jQuery equivalent of domcollapse
        if ($.browser.msie && parseInt($.browser.version) < 8) {
        	$("h3.trigger").toggleClass("triggerexpanded");
        	$("h3.trigger").toggleClass("trigger");
        } else {
        	$("h3.trigger").next().hide();
        }
		
		// Make the requestInfo button's href into a Thickbox link 
		$("a[href=#requestInfo]").attr("href","#TB_inline?height=600&width=500&inlineId=requestInfo");
		
		// Set up Lightbox for image galleries 
		var lightboxImagePath = cwsConfig.contextPath + 'icons/platform/jquery-lightbox/'; 
		$('a[rel*=lightbox]').lightBox({
			imageLoading: lightboxImagePath + 'lightbox-ico-loading.gif',
			imageBtnPrev: lightboxImagePath + 'lightbox-btn-prev.gif',
			imageBtnNext: lightboxImagePath + 'lightbox-btn-next.gif',
			imageBtnClose: lightboxImagePath + 'lightbox-btn-close.gif',
			imageBlank: lightboxImagePath + 'lightbox-blank.gif'
    	});
		
		if ($.browser.msie) {
			$("#buyersguide #categoryList li").append("|&nbsp;");
		}
		
		if ($("form.validate").size() > 0) {
			$("form.validate").validate({
				errorElement: "em",
				success: function(element){
					element.parent().find("input").addClass("fieldOk");
					
				},
				highlight: function(element, errorClass) {
					$(element).addClass(errorClass);
					$(element).removeClass("fieldOk");
				},
				unhighlight: function(element, errorClass) {
					$(element).removeClass(errorClass);
					$(element).addClass("fieldOk");
				}
			});
		}
		
		/* product enquiry form completion tracking - czb
		   category,action and label */		
		$("#buyersguide #requestInfoLink").click(function(){			
			var pc = $('[name=productCode]').val();
			AllUsers.trackEvent('readerEnquiry','viewForm', pc);
		});
		
		$("#buyersguide .button").click(function(){
			if ($("form.validate").size() > 0) {
				var pc = $('[name=productCode]').val();
				AllUsers.trackEvent('readerEnquiry','submitForm', pc);
			}
		});
		
		// Use parent-child (elem1 > elem2) selectors to make sure we only
		// select the top-level categories' links  
		$(".categoryExplorer > ul > li > a").click(function(){
			$(this).parent().toggleClass('expanded').find("ul").toggle();
			return false;
		});
		
		$("blockquote.spam").before('<a href="#" class="showSpam">Show message</a>');
		$("blockquote.spam").parent().find("a.showSpam").click(function(){
			$(this).nextAll("blockquote.spam").toggle();
			if ($(this).text() == 'Show message'){
				$(this).text('Hide message');
			}
			else {
				$(this).text('Show message');
			}
			return false;
		});
		
		AllUsers.micrositeSelectedNavigation();
    },
    
	/**
	 * @id AllUsers.addDateWidgets
	 * @author tim.beadle@iop.org
	 */
    addDateWidgets: function(){
        var today = new Date();
        var lastYear = today.getFullYear() - 1;
        $(".date-picker").datePicker({
            inputClick: false,
            startDate: '01/01/' + lastYear
        });
        $(".date-picker-nopastdates").datePicker({
            inputClick: false
        });
    },
    
	/**
	 * @id AllUsers.attachEvents
	 * @author tim.beadle@iop.org
	 */
    attachEvents: function(){
        var e = encodeURIComponent;
        var d = document;
        var t = d.title;
        
        /*
         * Google Analytics: track outbound links from company and product pages
         * 
         * If the current document's URL matches a company page (normal listing 
         * or microsite page), add the click event UNLESS it's an a.outbound, or
         * we'll end up with two click events (and therefore double counting!)
         */
        var urlPattern = /(company|product)\/([A-Z][0-9]{9})/;
        if (d.URL.match(urlPattern)) {
            $("#content a[href^=http]").not("a.outbound").click(function(){
                d.URL.match(urlPattern);
                AllUsers.trackOutboundLink(RegExp.$1,RegExp.$2,this.href);
            });
        }
        
        /*
         * Also attach the function to the click event of a.outbound elements, 
         * for situations (e.g. lists of assets) where the assetType and 
         * assetCode can't be divined from the page url
         */
        $("a.outbound").click(function(){
        	var asset = this.id.split(":");
        	AllUsers.trackOutboundLink(asset[0],asset[1],this.href);
        });
        
        $("form.downloadRequest").submit(function(){
        	AllUsers.trackPageview('/download/' + document.location.href);
        	
        });
        
        // domcollapse general rules
        $("h3.trigger").mouseover(function(){
            $(this).addClass("triggerhover");
        });
        
        $("h3.trigger").mouseout(function(){
            $(this).removeClass("triggerhover");
        });
        
        // domcollapse for form elements
        $("fieldset h3.trigger").click(function(){
        	
            $(this).next().toggle();
            $(this).toggleClass('triggerexpanded');
            $(this).toggleClass('trigger');
        });
        
        // domcollapse for contact section
        $("#contact h3.trigger").click(function(){
            $(this).next().toggle("slow");
            $(this).toggleClass('triggerexpanded');
            $(this).toggleClass('trigger');
        });
        
        // Subject filter nav expand/collapse
        $("#subjectNav h3").click(function(){
            $("#subjectNav ul").toggle('fast');
            $("#subjectNav h3").toggleClass('collapso');
            $("#subjectNav h3").toggleClass('expando');
        });
        
        // Social bookmarks (They no longer use JavaScript I believe - redundant?)
        $("a.delicious").click(function(){
            var a = AllUsers;
            a.openWin(a.serviceUrl(this.href) + '?v=4&noui&jump=close&url=' +
            $.getURLParam(this.href, "url") +
            '&title=' +
            e(t));
            return false;
        });
        
        $("a.citeulike").click(function(){
            var a = AllUsers;
            a.openWin(a.serviceUrl(this.href) + '?url=' +
            $.getURLParam(this.href, "url") +
            '&title=' +
            e(t), {
                width: 800,
                height: 550
            });
            return false;
        });
        
        $("a.furl").click(function(){
            var a = AllUsers;
            a.openWin(a.serviceUrl(this.href) + '?u=' +
            $.getURLParam(this.href, "u") +
            '&t=' +
            e(t));
            return false;
        });
        
        $("a.connotea").click(function(){
            AllUsers.openWin('http://www.connotea.org/addpopup?continue=confirm&uri=' +
            $.getURLParam(this.href, "uri") +
            '&title=' +
            e(t), {
                width: 660,
                height: 600
            });
            return false;
        });
        
        $("a.bibsonomy").click(function(){
            var a = AllUsers;
            var h = a.serviceUrl(this.href) + '?c=b&jump=yes&url=' +
            $.getURLParam(this.href, "url") +
            '&description=' +
            e(t);
            if (!utils.isEmpty(a.getSelection())) {
                h += '&extended=' + e(a.getSelection());
            }
            a.openWin(h, {
                width: 750,
                height: 500
            });
            return false;
        });
        
        $("a.magnolia").click(function(){
            var a = AllUsers;
            var h = 'http://ma.gnolia.com/bookmarklet/popup/add?url=' +
            $.getURLParam(this.href, "url") +
            '&title=' +
            e(t);
            if (!utils.isEmpty(a.getSelection())) {
                h += '&description=' + e(a.getSelection());
            }
            a.openWin(h, {
                width: 800,
                height: 550
            });
            return false;
        });
        
        $("a.digg").click(function(){
            var a = AllUsers;
            var h = this.href;
            if (!utils.isEmpty(a.getSelection())) {
                h += '&description=' + e(a.getSelection());
            }
            a.openWin(h, {
                width: 800,
                height: 550
            });
            return false;
        });
        
        // Add the close button to the previously registered div
        $("#previouslyRegistered").prepend('<a href="#" class="close">Close</a>');
        $("#previouslyRegistered a.close").click(function(){
            $("#previouslyRegistered").slideUp('fast');
            $("#previouslyRegistered a.close").css({
                'background-color': '#aa9'
            });
            return false;
        });
    },
    
    initGalleria: function(){
    	
    	$('.gallery_unstyled').addClass('gallery'); // adds new class name to maintain degradability
    	
    	$('ul.gallery').galleria({
    		history   : true, // activates the history object for bookmarking, back-button etc.
    		clickNext : true, // helper for making the image clickable
    		insert    : '#main_image', // the containing selector for our main image
    		onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
    			
    			// fade in the image & caption
    			image.css('display','none').fadeIn(1000);
    			caption.css('display','none').fadeIn(1000);
    			
    			// fetch the thumbnail container
    			var _li = thumb.parents('li');
    			
    			// fade out inactive thumbnail
    			 _li.siblings().children('img.selected').fadeTo(500,0.3);
    			
    			// fade in active thumbnail
    		thumb.fadeTo('fast',1).addClass('selected');
    			
    			// add a title for the clickable image
    			image.attr('title','Next image >>');
    		},
    		onThumb : function(thumb) { // thumbnail effects goes here
    			
    			// fetch the thumbnail container
    			var _li = thumb.parents('li');
    			
    			// if thumbnail is active, fade all the way.
    			var _fadeTo = _li.is('.active') ? '1' : '0.3';
    			
    			// fade in the thumbnail when finnished loading
    			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
    			
    			// hover effects
    			thumb.hover(
    				 function() { thumb.fadeTo('fast',1); },
    				 function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
    			)
    		}
    	});
    },

    /**
     * @id AllUsers.trackOutboundLink
     * tracks outbound links
     */
    trackOutboundLink: function(assetType, assetCode, assetUrl) {
    	var outboundUrl = '/outbound/'+assetType+'/'+assetCode+'/'+assetUrl;
    	AllUsers.trackPageview(outboundUrl);
    },

    /**
     * @id AllUsers.trackPageview(url)
     * wrapper function around the Google Analytics _trackPageview method
     */
    trackPageview: function(url) {
    	var tracker = _gat._getTracker(ga_acct);
    	tracker._initData();
    	tracker._trackPageview(url);
    },

    /**
     * @id AllUsers.trackEvent(url)
     * wrapper function around the Google Analytics _trackEvent method
     */
    trackEvent: function(a, b, c) {
    	var tracker = _gat._getTracker(ga_acct);
    	tracker._initData();
    	tracker._trackEvent(a, b, c, 0);
    },

    /**
     * @id AllUsers.getSelection
     */
    getSelection: function(){
        var selection = '';
        if ($.browser.msie) {
            selection = document.selection.createRange().text;
        }
        else if ($.browser.safari || $.browser.mozilla) {
            selection = window.getSelection();
        }
        return String(selection).replace(/%20{2,}/g, '%20').replace(/^%20|%20$/g, '');
    },
    
    /**
     * @id AllUsers.openWin
     * @author tim.beadle@iop.org
     * @param {String} href the URL to open
     * @param {Object} opts object containing option (currently limited to width and height) 
     */
    openWin: function(href, opts){
        if (opts === undefined) {
            opts = {
                width: 700,
                height: 400
            };
        }
        window.open(href, 'socialBookmarks', 'scrollbars=yes,toolbar=no,width=' + opts.width + ',height=' + opts.height);
    },
    
    serviceUrl: function(uri){
        return uri.split('?')[0];
    },
    
    /**
     * restrictArticleElementWidth
     * 		polls the width of an article element (usually an image) and
     * 		makes its parent container the same width, making the layout
     * 		much tidier
     */
    restrictArticleElementWidth: function(){
        var imgWidth = $(".articleElement img").width();
        if (imgWidth > 200) {
            $(".articleElement").width(imgWidth);
        }
    },
    
    /**
     * enhanceInstituteLogin
     * 		Replaces the default "Sign in with Institute of Physics username
     * 		and password" checkbox with a tabbed user interface
     */
    enhanceInstituteLogin: function(){
        var siteName = $("meta[name=title]").attr("content");
        var preLoginText = {
            iop: "You're about to sign in with your " + siteName + " username and password.",
            cws: "You're about to sign in with an Institute of Physics username and password."
        };
        var loginText = {
            iop: "Sign in here",
            cws: "Go back to " + siteName + " sign-in"
        };
        var username = {
            iop: "Institute username",
            cws: siteName + " username"
        };
        var password = {
            iop: "Institute password",
            cws: siteName + " password"
        };
        
        var toggler = '<div id="toggleLogin">' +
        	'<p>Please choose from the following sign-in methods:</p>' +
        	'<ul>'+
        		'<li><a href="#" id="cws" class="selected">' + siteName +
        		' sign-in</a></li>' +
        		'<li><a href="#" id="iop">IOP Member sign-in</a></li>' +
        	'</ul>' +
        	'<p id="preLogin">' + preLoginText.iop + '</p>' + 
        '</div>';
        
        $("#instituteLogin").parent().hide().before(toggler);
        AllUsers.toggleLoginLabels(username.cws, password.cws);
        $("#iopForgotPassword").hide();
        
        $("#toggleLogin a").click(function(){
            var thisTab = $(this).attr('id');
            var thatTab = thisTab == 'iop' ? 'cws' : 'iop';
            // Add "selected" class to clicked link, and
            $(this).addClass('selected');
            // Remove "selected" from other link
            $("#" + thatTab).removeClass('selected');
            $("#toggleLogin p#preLogin").empty().prepend(preLoginText[thatTab]);
            
            AllUsers.toggleLoginLabels(username[thisTab], password[thisTab]);
            if (thatTab == 'cws') {
                $("#instituteLogin").check();
                $("#cwsForgotPassword").hide();
                $("#iopForgotPassword").show();
            }
            else {
                $("#instituteLogin").uncheck();
                $("#iopForgotPassword").hide();
                $("#cwsForgotPassword").show();
            }
            return (false);
        });
        
    },
    
    /**
     * toggleLoginLabels
     * 		Swaps the username and password labels for new text
     *
     * @param {String} usernameLabelText
     * 		The replacement text for the username label
     *
     * @param {String} passwordLabelText
     * 		The replacement text for the password label
     */
    toggleLoginLabels: function(usernameLabelText, passwordLabelText){
        // Swap the username label
        $("label[for=userName]").empty().prepend(usernameLabelText);
        // Swap the password label
        $("label[for=passWord]").empty().prepend(passwordLabelText);
    },
    
    /**
     * showCharsRemaining
     *		Shows the number of characters remaining before a field's
     *		maxLength is reached
     *
     * @param {Object} formElement
     * 		the form element object
     *
     * @param {String} formElement
     * 		the form element object's id
     */
    showCharsRemaining: function(formElement){
        if (typeof(formElement) == 'string') {
            formElement = document.getElementById(formElement);
        }
        // Determine the maxLength
        var maxLength = $(formElement).parent().find('span em').text();
        // Determine whether we should use a Threshold
        var threshold = 0;
        if ($(formElement).parent().is('.stealth')) {
            threshold = Math.round(maxLength * 0.75);
        }
        // Indicate characters remaining when above threshold
        var realLength = utils.normalizeCRLF(formElement.value).length;
        if (realLength > threshold) {
            var remaining = maxLength - realLength;
            var characters = (remaining == 1 || remaining == -1) ? 'character' : 'characters';
            
            var label, css;
            if (remaining >= 0) {
                label = remaining + ' ' + characters + ' remaining';
                css = {
                    'background-color': '#fff933',
                    'color': '#000'
                };
            }
            else {
                label = 'Please remove ' + (remaining * -1) + ' ' + characters;
                css = {
                    'background-color': '#000',
                    'color': 'white'
                };
            }
            
            $("label[for=" + formElement.id + "] em").empty().append(label).css(css);
        }
        else {
            $("label[for=" + formElement.id + "] em").empty();
        }
    },
    
    /**
     * micrositeSelectedNavigation
     */
    micrositeSelectedNavigation : function(){
    	if ($("body").hasClass("newMicrosite") && $.browser.msie === false){
    		var currentPage = $("#micrositeContainer").attr("class");
    		$("ul.main-navigation li a").each(function(){
    			var pageNav = $(this).attr("href").split("/").pop();
    			if (pageNav === currentPage){
    				$(this).parent().addClass("selected");
    			}
    		});
    	}
    }
};

// Attach the init method to the document.ready event
$(document).ready(AllUsers.init);

