$(document).ready(function () {
    $('body').addClass('js_enabled');

    DBCDE.TopNav();
    DBCDE.SelectLanguage();
    DBCDE.SuperSelectify()
    DBCDE.SearchBox();
    DBCDE.TextSize();
    DBCDE.PIE();
    DBCDE.HomeCarousel();
    DBCDE.LocalScroll();
    DBCDE.Forms();
    DBCDE.ExpandingList();
    DBCDE.Tabs();
    DBCDE.FAQs();
    DBCDE.Videos();
    DBCDE.VideoTutorial();
	DBCDE.MultiMediaVideo();
    DBCDE.ProductSearch();
    DBCDE.TrackDocumentClicks();
    
    DBCDE.DisableRightClick();
    $("#topnav .searchBox .button").click(function () {
        $(".carouselContent #heroCarousel_1").fadeOut(2000)
    });
	


});


var DBCDE = {};

DBCDE.Config = {
	flashPlayer: "/App_Themes/Digitalready/swf/player.swf"
};

DBCDE.Utility = {};

/**
 * Get a URL Param value based on a variable name 
 */
DBCDE.Utility.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (!results) { return 0; }
	return results[1] || 0;
}

/**
 * Check if the current client is IE 6
 */
DBCDE.Utility.isIE6 = function() {
	if ($.browser.version == "6.0" && $.browser.msie) { 
		return true;
	}
	return false;
}

/**
	Help out IE by applying a behavior to certain elements to it can have rounded
	corners applied via CSS.
*/


var pieSelectorsArray = [
					".sidebar .pod:last-child .content",
					".sidebar .pod:first-child h3",
					"#content .pod.secondary h3",
					"#mySwitch .nextRegion",
					"#sidenav ul.CMSListMenuUL li.CMSListMenuHighlightedLI",
					"#footer .content, #pageheader",
					".brandpod",
					".brandcorners",
					"#sidenav",
					"#homeLatestNews .grid_1,",
					"#homeLatestNewsContainer .grid_1",
					"#homeLatestNewsContainer .homeLatestNews h3",
					"#content .tinypod",
					"#content .pod.standalone h3",
					"#content .pod.standalone .content",
					"#switchOverMap"
				];
var pieSelectors = pieSelectorsArray.join(",");

function Printfix(){
   
    window.onbeforeprint = removeRoundedboxes;
    window.onafterprint = addRoundedboxes;
}

function removeRoundedboxes(){
	$(pieSelectors).css("behavior","none");
}
    
function addRoundedboxes(){
	$(pieSelectors).css("behavior","url(/App_Themes/DigitalReady/css/PIE.htc)");
}

DBCDE.PIE = function() {
	
					
	if ($.browser.msie) {
		Printfix();
		//$(selectors).css("behavior","url(/App_Themes/DigitalReady/css/PIE.htc)");
	}
};

/**
 *	Disbale Right Click contextmenu for certain elements
 */
DBCDE.DisableRightClick = function() {
	
	$('#nonRightClickSection').bind("contextmenu",function(e){
		return false;
	});
	
}
/**
 *	Home Carousel handler
 */
DBCDE.HomeCarousel = function() {
	

	this.theOptions = {
		fx: [
			{opacity:['toggle'], duration:'fast'}, 
			{opacity:['toggle'], duration:'normal'}
		],
		selected:0
	}
	
	if (DBCDE.Utility.isIE6()) { 
		this.theOptions.fx = [];
	}
	
	this.init = function() {
		this.carousel = $("#heroCarousel");
		this.carousel.tabs(this.theOptions);
		this.carousel.tabs("rotate", 13000);
		this.count = this.carousel.find(".carouselContent li").length;

		that = this;
		this.carousel.find(".btn.next").click(function() { that.moveNext(); return false; });
		this.carousel.find(".btn.prev").click(function() { that.movePrev(); return false; });
	}
	
	this.moveNext = function() {
		sel = this.carousel.tabs("option", "selected");
		next = sel + 1;
		
		if (sel >= (this.count - 1)) { 
			next = 0;
		}
		
		this.carousel.tabs("option", "selected", next);
		this.carousel.tabs("rotate", 0)
	}

	this.movePrev = function() {
		sel = this.carousel.tabs("option", "selected");
		next = sel - 1;
		
		if (sel < 1) {
			next = this.count - 1;
		}
		
		this.carousel.tabs("option", "selected", next);
		this.carousel.tabs("rotate", 0)
	}
	
	this.init();
	
};


/**
 *	Adds classes with same/similar names for CSS3 selectors
 */
DBCDE.SuperSelectify = function() {
	
	$(document).superSelectify({
		manualSelectors:
			".sidebar .pod:first-child, "+
			".sidebar .pod:last, "+
			"input[type='text'], " +
			"#homeLatestNewsContainer .homeLatestNews:first-child, " +
			"#homeLatestNewsContainer .homeLatestNews:last-child"
	});
	
};


/**
 * Search Box functionality
 */
DBCDE.SearchBox = function() {

	//hide the search label if there is a value in the field.
	$searchBox = $(".searchBox");
	$searchBox.each(function(k,v) {
		var $field = $(v).find("input.search")
		var $label = $(v).find("label")
		if ($field.val() != "") {
			$label.hide();
		}
		$field.focus(function() { $label.hide(); })
		$field.blur(function() {
			if ($field.val() == "") {
				$label.show();
			}
		})
	});
	
	
};

/**
*	Language Selector drop down
*/

/**
*	Language Selector drop down (OLD HOVER)
 */
DBCDE.SelectLanguage = function() {
	
	function init() { 
		
		var config = {    
			sensitivity: 2,
			interval: 10, 
			over: showDropdown,    
			timeout: 500,  
			out: hideDropdown 
		};
		
		var focusTriggered = false;
				
		$("#toolLanguage").hoverIntent(config);
		$("#toolLanguage .languageSelection a").attr("href", "");
	}
		
	var showDropdown = function(el){
		$t = $(this);
		$t.addClass("hover");
		$t.find(".languageSelectionPanel").fadeIn(300);
	}	
	
	var hideDropdown = function(el){
		$t = $(this);
		$t.removeClass("hover");
		$t.find(".languageSelectionPanel").fadeOut(300);
	}

	init();
};


/**
 *	Drop down menus for the top nav.
 */
DBCDE.TopNav = function() {
	
	var config = {
		rowLen: 2
	}

	var init = function() {

		var config = {    
			sensitivity: 1,
			interval: 50, 
			over: megaHoverOver,    
			
			out: megaHoverOut 
		};
	
		$("ul#topnav li .sub").css({'opacity':'0'});
		$("ul#topnav li").hoverIntent(config);
		
		//makeRows();
		
		addSpacerRows();
	}
	
	var megaHoverOver = function(){
		$t = $(this);
		$sub = $t.find(".sub");
		$sub.stop().fadeTo(200, 1).show().closest("li").addClass("hasSubNav hovered");

		//set the width based on the [rowlength] # of ULs -- but only if there is a sub
		if ($sub.length > 0) {

			leftOffset = $t.offset().left;
			ww = $(window).width() - 20; // the (- x) = the shadow blur width

			right = "auto";
			if ((leftOffset + 420) > ww) {
				right = -100;
				$sub.css({"left": "auto", "right": right  });
			}
		}

	}	
	
	var megaHoverOut = function(){
		$t = $(this);
		$t.removeClass("hovered");
		
		$t.find(".sub").stop().fadeTo(200, 0, function() { 
			$(this).hide(); 
		});
	  
	}
	
	var addSpacerRows = function() {

		$("ul#topnav li .sub.wide").each(function() {
			//every rowLen(th) ul, add a div.spacer
			$(this).find("ul:nth-child(2n)").after("<div class='spacer'></div>");
		});
		
	};
	var makeRows = function() {
		
		$("ul#topnav li .sub").each(function() {
			
			t = $(this).parent().find("a:first").text();
			var ulCount = ($(this).find('ul')).length;
			divs = ulCount % config.rowLen;
		
			$("#sidebar .inner").append("<p>"+ t +": divs: "+divs+"</p>");

			if (divs > 0) {
				//lets see how many sets we have...
				sets = Math.ceil(ulCount / config.rowLen);

				//make a new row and place x amount of uls in it.
				for (var i=0;i < sets; i++) {
					el = $("<div class='row'></div>");
					$sliced = $(this).children('ul').slice(0,config.rowLen).appendTo(el);
					$(el).appendTo(this);
				}
			}

			divs = 0;
		});
		
	}
	
	
	init();
	
};


/**
 *	Text Sizer - applies a class to the body which can be used to
 *	increase/decrease the text size on the page
 */
DBCDE.TextSize = function(strSize, doBind) {

	var COOKIE_NAME = "dbcde_tr",
		PREFIX = "textsize_",
		options = { path: "/", expires: 10 },
		defaultSize = "textsize_1",
		count = $("#toolTextsize a").length,
		cookieSet = false.
		cookieVal = "";
			
	if (strSize == undefined || strSize == null) {
		//get the current cookie and set the active stylesheet
		if ($.cookie(COOKIE_NAME) != "" && $.cookie(COOKIE_NAME) != undefined) {
			cookieVal = $.cookie(COOKIE_NAME)
			//only set it active on initial load if it's been set before.
			$("#"+cookieVal).addClass("active");
		}
		else {
			cookieVal = defaultSize;
		}
		DBCDE.setActiveStyleSheet(cookieVal);
			
		bindLinks();
	}
	else {
		$.cookie(COOKIE_NAME, strSize, options);
		DBCDE.setActiveStyleSheet(strSize);
		$("#"+strSize).addClass("active");
	}


	function bindLinks() {

		$("#toolTextsize a").click(function(e){
			e.preventDefault();
			$t = $(this);
			cookieVal = $t.attr("id");
			
			DBCDE.TextSize(cookieVal);
			
			$t.parent().find("a").removeClass("active");
			$t.addClass("active");
			
			return false;
		});		

	}
	
};

DBCDE.ContrastSwitch = function(type, doBind) {


	var COOKIE_NAME = "dbcde_contrast",
		PREFIX = "contrast_",
		options = { path: "/", expires: 10 },
		contrasts = ["contrast_normal", "contrast_high"]
		cookieSet = false.
		cookieVal = "";
			
	if (type == undefined || type == null) {
		//get the current cookie and set the active stylesheet
		if ($.cookie(COOKIE_NAME) != "" && $.cookie(COOKIE_NAME) != undefined) {
			cookieVal = $.cookie(COOKIE_NAME)
			//only set it active on initial load if it's been set before.
			$("#"+cookieVal).addClass("active");
		}
		else {
			cookieVal = contrasts[0];
		}
		DBCDE.setActiveStyleSheet(cookieVal);
			
		bindLinks();
	}
	else {
		$.cookie(COOKIE_NAME, strSize, options);
		DBCDE.setActiveStyleSheet(strSize);
		$("#"+strSize).addClass("active");
	}


	function bindLinks() {

		$("#toolTextsize a").click(function(e){
			e.preventDefault();
			$t = $(this);
			cookieVal = $t.attr("id");
			
			DBCDE.TextSize(cookieVal);
			
			$t.parent().find("a").removeClass("active");
			$t.addClass("active");
			
			return false;
		});		

	}
	
}

DBCDE.setActiveStyleSheet = function(title, disableSheet) {
	var i, a, main;
	
	if (disableSheet != undefined || disableSheet != null) {
		$("head link[rel][title='"+disableSheet+"']").attr("disabled",true);
		$("head link[rel][title='"+title+"']").attr("disabled",false);
	}
	
	$("head link[rel][title]").each(function(k,v){
		$v = $(v)

		if($v.attr("rel").indexOf("alternate style") != -1) {
			$v.attr("disabled",true);
			if($v.attr("title") == title) {
				$v.attr("disabled",false);
			}
		}

	});
}

/** LocalScroll
 *  enables in-page-scrolling, a usability feature that allows users
 *  to always to have a good sense of where they are on the page.
 */
DBCDE.LocalScroll = function() {
	$(".internalLinks, .top").localScroll();
}

/** Forms
 * 	Adds event handlers to the form rows to handle showing/hiding of error messges.
 * 	Also makes the list of errors clickable so they provide direct access to the
 * 	element requiring attention.
 */
DBCDE.Forms = function() {

	$(".form", "#content").find(".row .errorMessage p span").closest(".row").addClass("error");
	
	$(".form", "#content").delegate(".row.error", "errorRowFocused errorRowBlurred", function(e) {
		$(this).closest(".form").find(".focused").removeClass("focused");
		switch (e.type) {
			
			case "errorRowFocused":
				$(this).addClass("focused");
				break;

		}
	});

	$(".form .row.error").mouseenter(function() { $(this).addClass('hovered'); $(this).trigger("errorRowFocused"); });
	$(".form .row.error input, .form .row.error select, .form .row.error textarea ").focus(function() {
		$(this).addClass("focused"); //want to know if form elements have focus
		$(this).closest(".row.error").trigger("errorRowFocused");
	});

	$(".form .row.error").mouseleave(function() {  $(this).removeClass('hovered'); $(this).trigger("errorRowBlurred"); });
	$(".form .row.error input, .form .row.error select, .form .row.error textarea ").blur(function() {

		$(this).removeClass("focused");
		$(this).closest(".row.error").trigger("errorRowBlurred");
	});
	
	$("#content .form .errors").delegate("a", "click", function() {
		$t = $(this);
		$("#" + $t.attr("rel")).focus();
		
	});

};

/**	ExpandingList
 *	Finds expandable lists and binds all the events required
 */
DBCDE.ExpandingList = function()  {
	$(".expandingLists > ul li").delegate("a.ExpandingAnswer", "click", function(e) {
		e.stopPropagation();
		$(this).parent().toggleClass("expanded").find(">.content").slideToggle(500); 
		return false;
	});
	
	$(".expandingLists .expandcollapse a").click(function() {
		$t = $(this);
		if ($t.hasClass("expand")) {
			$(".expandingLists > ul li .content").show();
			$(".expandingLists > ul > li, .expandingLists > ul > li ul > li").addClass("expanded");
		}
		else {
			$(".expandingLists > ul li .content").hide();			
			$(".expandingLists > ul > li, .expandingLists > ul > li ul > li").removeClass("expanded");
		}
	});
};


/** FAQFinder
 * Finds a particular FAQ Item on the page based on its rel attribute and expands it and its parent

 * (by triggering clicks that are set up in DBCDE.ExpandingList)
 * The element is then scrolled to using the scrollTo plugin.
 */
DBCDE.FAQs = function() {
	
	
	$faqTabs = $("#mainTabs");
	
	var hash = window.location.hash,
		$theQuestion = {};
	
	if (hash != "") {
		hash = hash.replace("#","");
		
		$theQuestion = $("a[rel="+hash+"]:first", "#FAQList");
		if ($theQuestion.is("a")){
			//switch to the Browse Tab
			$faqTabs.tabs("select",1);
			$theQuestion.trigger("click").closest(".content").parent().find("a:first").trigger("click");
			$theQuestion.attr("id", hash).delay(600).queue(function() {
				$.scrollTo("#"+hash, {duration:1000});
			});
		}
	}
	
	//faq search collapser
	$("#faqSearchResults").delegate(".theFaqSearchQuestion a", "click", function(e) {
		e.stopPropagation();
		$(this).closest(".searchResult").toggleClass("expanded").find(">.theFaqSearchContent").slideToggle(500); 
		return false;
	});

	$("#faqSearchResults .expandcollapse a").click(function() {
		$t = $(this);
		if ($t.hasClass("expand")) {
			$("#faqSearchResults .theFaqSearchContent").show();
			$("#faqSearchResults .searchResult").addClass("expanded");
		}
		else {
			$("#faqSearchResults .theFaqSearchContent").hide();			
			$("#faqSearchResults .searchResult").removeClass("expanded");
		}
	});


}


/** Videos
 *	Builds the Carousel and puts the Media player on to the page.
 */
DBCDE.Videos = function () {


	// See http://flesler.blogspot.com/2008/02/jqueryserialscroll.html for documentation 
	$('#videoCarousel').serialScroll({
		target:'#videoList',
		items:'li', 
		prev:'.prev',
		next:'.next',
		axis:'y',
		duration:1000,
		force:true, 
		easing:"easeOutQuad",
		cycle:false,
		constant:false,
		onBefore:function( e, elem, $pane, $items, pos ){
			e.preventDefault();
		},
		exclude: 3,
		step:4
	});

	bindVideoLinks()

    function bindVideoLinks() {
        var options = {
            swf: "flash/StrobeMediaPlayback.swf",
            express: "flash/expressinstall.swf",
            width: 445,
            height: 250,
            src: "",
            autoPlay: false,
            playButtonOverlay: true,
            scaleMode: "none",
            backgroundColor: "transparent"
        };

        var flashvars = {
            src: "../video/charlietheunicorn_hottopic.flv",
            autoPlay: false,
            playButtonOverlay: true,
            scaleMode: "stretch",
            wmode: "transparent",
            backgroundColor: "transparent"
        };
        var params = {
            menu: "false"
        };
        var attributes = {
            allowScriptAccess: "always",
            allowFullScreen: true,
            wmode: "transparent"
        };
		var videoplayerDiv = "thePlayer";


        $("#videoList li a").click(function() {
            //get the href to the video
            var theSrc = $(this).attr("href");
            //if the source starts with a slash, make a full URL so the flvplayer understands it
            if (theSrc.charAt(0) == "/") {
                theSrc = window.location.protocol + "//" + window.location.host + theSrc;
            }
            localOpts = {
                src: theSrc
            };
            var localFlashVars = $.extend(flashvars, localOpts);
            
			swfobject.embedSWF(options.swf, videoplayerDiv, options.width, options.height, "10.0.0", options.express, flashvars, params, attributes);
			
            return false;
        });
		swfobject.embedSWF(options.swf, videoplayerDiv, options.width, options.height, "10.0.0", options.express, flashvars, params, attributes);		
    }

};

DBCDE.Tabs = function() {
	// set up standard tabs
	$(".tabs").tabs();

	//set up main content tabs.
	$("#mainTabs").tabs({fx: [
		{opacity:['toggle'], duration:'fast'}, 
		{opacity:['toggle'], duration:'normal'}
	]});

}

function getParameterByName( name ) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null ) {
        return "";
    }
    else {
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
}

DBCDE.MultiMediaVideo = function ()
{
	if ($("#video_tutorial_multimedia").is("div"))
	{
		var currentLocation = "http://" + window.location.host;

		var theLink = $('#video_tutorial_multimedia #video');
		var flashURL = theLink.attr('href');
		var captionsURL = theLink.attr('rel');

		var posterImage = $('#video_tutorial_multimedia img').attr('src');

		if (captionsURL.indexOf("00000000-0000-0000-0000-000000000000") == -1) // a real caption file instead of zeros
		{
			jwplayer("video_tutorial_multimedia").setup({
				flashplayer: DBCDE.Config.flashPlayer,

				file: flashURL,
				image: posterImage,
				width: 640,
				height: 380,
				controlbar: "bottom",
				skin: "/App_Themes/Digitalready/xml/controlbar2.zip",
				plugins: {
					'captions-2.0': {
						back: true,
						file: captionsURL,
						fontsize: 12,
						state: false,
						dock: true
					}
				}
			});
		}
		else // no captions
		{
			jwplayer("video_tutorial_multimedia").setup({
				flashplayer: DBCDE.Config.flashPlayer,

				file: flashURL,
				image: posterImage,
				width: 640,
				height: 380,
				controlbar: "bottom",
				skin: "/App_Themes/Digitalready/xml/controlbar2.zip"
			});
		}
	}
}

DBCDE.VideoTutorial = function () {
    if ($("#video_tutorial_video").is("div")) {
        var currentLocation = "http://" + window.location.host;
		
        var theLink = $('#video_tutorial_video #video');
        var flashURL = theLink.attr('href');
        var captionsURL = theLink.attr('rel');
		
		var theSignLanguageLink = $('#video_tutorial_video #signvideo');
		var signFlashUrl = theSignLanguageLink.attr('href');
		
        var posterImage = $('#video_tutorial_video img').attr('src');

        var relatedclipsXml = flashURL;

        relatedclipsXml = relatedclipsXml.substring(relatedclipsXml.lastIndexOf("/"));

        if (relatedclipsXml.indexOf(".") != -1) {
            relatedclipsXml = relatedclipsXml.substring(0, relatedclipsXml.indexOf("."));
        }

        relatedclipsXml = "/App_Themes/DigitalReady/xml" + relatedclipsXml + ".xml";

        if (UrlExists(relatedclipsXml)) {
            // file exists, so there is a playlist
            jwplayer("video_tutorial_video").setup({
                flashplayer: DBCDE.Config.flashPlayer,

                file: flashURL,
                image: posterImage,
                width: 640,
                height: 380,
                controlbar: "bottom",
                skin: "/App_Themes/Digitalready/xml/controlbar2.zip",
                plugins:{
					'captions-2.0': {
						back: true,
						file: captionsURL,
						fontsize: 12,	
						state :false,
						dock:true
					},
					'/App_Themes/Digitalready/js/sign_language_plugin.js': {
						sign_url: signFlashUrl,
						flash_url:flashURL
					},
					'drelated-1': {
						dxmlpath: relatedclipsXml,
						dposition: "bottom",
						dtarget: "_self",
						dskin: '/App_Themes/Digitalready/swf/grayskin.swf'
					}
				}
            });
        }
        else {
            // file does not exist so no playlist
            jwplayer("video_tutorial_video").setup({
                flashplayer:  DBCDE.Config.flashPlayer,

                file: flashURL,
                image: posterImage,
                width: 640,
                height: 380,
                controlbar: "bottom",
                skin: "/App_Themes/Digitalready/xml/controlbar2.zip",
				plugins:{
					'captions-2.0': {
						back: true,
						file: captionsURL,
						fontsize: 12,	
						state :false,
						dock:true
					},
					'/App_Themes/Digitalready/js/sign_language_plugin.js': {
						sign_url: signFlashUrl,
						flash_url:flashURL
					}
				}				
            });
        }
		
        if ($("#previousVid a").attr('href') == '') {
            $("#previousVid").remove();
        }

        if ($("#nextVid a").attr('href') == '') {
            $("#nextVid").remove();
        }
		
    }
}

DBCDE.StandaloneVideoPlayer = function (videoPlayerId) {
	var currentLocation =  "http://" + window.location.host,
		theLink,
		videoURL = "",
		captionsURL = "",
		posterImage,
		pluginString = "",
		playerOptions = {};
	
	
	theLink = $("#" + videoPlayerId + ' a');
	videoURL = theLink.attr('href');
	captionsURL = theLink.attr('rel');
	posterImage = $("#" + videoPlayerId + ' a img').attr('src');

	playerOptions = {
		flashplayer: 	DBCDE.Config.flashPlayer,
		file: 			videoURL,
		image: 			posterImage,
		width: 			640,
		height: 		384,
		controlbar: 	"over",
		dock: 			false,
		autostart: 		false,
		provider: 		"video",
		controlbar:		"bottom",
		plugins: 		{}
	}
	
	if (captionsURL != "" && captionsURL != undefined) {
		playerOptions.plugins = {
			"captions-2.0": {
			   'file': captionsURL,
			   "back": true,
			   "fontSize": 12,
			   "state": false
			}
        };
	
	}

	jwplayer(videoPlayerId).setup(playerOptions);
}

function UrlExists(url) {
	var http = new XMLHttpRequest();
	http.open('HEAD', url, false);
	http.send();
	return http.status != 404;
}

DBCDE.ProductSearch = function() {
	if ($("#productSearchFilter").is("div")) {
		
		
		$("#toggleMoreOptions").live("click", function() {
			that = $(this);
			$("#moreOptions .moreOptionsInner").slideToggle(600, function() {
				vis = $(this).is(":visible");
				that.toggleClass("open", vis);
			});
			
			return false;
		});
		
		$("#moreOptions span.help").hover(function() { $(this).find("p").show(); }, function() { $(this).find("p").hide(); });

		pagesize= DBCDE.Utility.urlParam("pagesize");
		
		if( DBCDE.Utility.urlParam("type") == "tv"){
			 // add parser through the tablesorter addParser method 
			$.tablesorter.addParser({ 
				// set a unique id 
				id: 'size', 
				is: function(s) { 
					// return false so this parser is not auto detected 
					return false; 
				},
				format: function(s) { 
					// format your data for normalization 
					
					return s.toLowerCase().substring(0,3)
				}, 
				// set type, either numeric or text 
				type: 'numeric' 
			}); 
			$("table.tablesorter").tablesorter({headers: { 2: {sorter:'size'}}, sortList: [[0,0]],widthFixed:true, widgets:["zebra"]}).tablesorterPager({container: $("#pager"), positionFixed:false, size: pagesize}); 
		}
		else{
			$("table.tablesorter").tablesorter({sortList: [[0,0]],widthFixed:true, widgets:["zebra"]}).tablesorterPager({container: $("#pager"), positionFixed:false, size: pagesize}); 
		}
		
		
		
		//If More Options, then slide the option open
		if (getParameterByName("brand") != "" || getParameterByName("screensize") != "" || getParameterByName("energyrating") != ""){
			$("#moreOptions .moreOptionsInner").slideToggle(0, function() {
				vis = $(this).is(":visible");
				$(this).toggleClass("open", vis);
			});
		}
		
		//If no pagesize, remove the sorter and pagination areas
		if(pagesize < 1){
			$(".tablesorter").addClass("displayNone");
			$("#pager").addClass("displayNone");
		}
	}
}

DBCDE.ImageGallery = function() {
	
	if ( !$("#imageGallery").is("div") ) {
		return;
	}
	
	$(".row .item:last-child").addClass("last");
	var maxHeight = 0;
	$(".row").each(function() {
	
		$(this).find(".item").each(function() {
			maxHeight = Math.max(maxHeight, $(this).outerHeight());
		});
		$(this).height(maxHeight).addClass("heighted");
	});
			
	$('#imageGallery a.gallery').lightBox({
		fixedNavigation:true,
		imageBlank: '/App_Themes/DigitalReady/img/lightbox/lightbox-blank.gif',
		imageLoading: '/App_Themes/DigitalReady/img/lightbox/lightbox-ico-loading.gif',
		imageBtnClose: '/App_Themes/DigitalReady/img/lightbox/lightbox-btn-close.gif',
		imageBtnPrev: '/App_Themes/DigitalReady/img/lightbox/lightbox-btn-prev.gif',
		imageBtnNext: '/App_Themes/DigitalReady/img/lightbox/lightbox-btn-next.gif'
	});
}


DBCDE.TrackDocumentClicks = function() {

    $("#content a").each(function() {
        var strLink = $(this).attr("href");

        // check if its a link to one of our list
        if (DBCDE.IsLocalTrackableLink(strLink)) {
        
            $(this).click(function(e) {
                // run the google page view function
                pageTracker._trackPageview(strLink);
            });
        }
		
    });
}

DBCDE.IsLocalTrackableLink = function(linkUrl) {
    // check that a link is not null, local, 
    // and contains our file extensions
    if (linkUrl != null && 
        linkUrl.indexOf("http://") < 0 && 
        linkUrl.match(/^(\/Content\/Documents\/|\/getattachment\/)(.*)$/gi)) {
        return true;
    }
    return false;
}	


DBCDE.SwitchoverMap = function(){
	var s = {}, 
		$map = $("#switchOverMap"),
		$legend = $map.find("ul");
		
	$.get("/App_Themes/Digitalready/js/switchovermap.optimised.xml", function(r){
		
		$(r).find("path").each(function() {
			$t = $(this);
			s[$t.attr("id")] = {
				path:		$t.attr("d"),
				title:		$t.find("title").text(),
				color:		$t.attr("fill"),
				hovercolor:	$t.attr("onmouseover"),
				link:		$t.find("link").attr("href")
			};
			
		});
		$map.append("<div id='paper'/>");
		if (Raphael.type !== "") {
			$legend.empty();
			renderMap(s);
		}
	}, "xml");

	
	function renderMap(data) {
		
		
		var R = Raphael("paper", 500, 450);
		//set some default attributes
		var attr = {
			fill: "#333",
			stroke: "#ccc",
			"stroke-width": 1,
			"stroke-linejoin": "round"
		};
		
		var aus = [];
		
		for (var tmp in data) {
			aus[tmp] = R.path(data[tmp].path).attr(attr);	
		}
		

		var current = null;
		
		for (var area in aus) {
	
			aus[area].color = s[area].color;
			aus[area].hovercolor = "#333";//s[area].hovercolor;
			aus[area].attr({fill:aus[area].color});
			aus[area].link = s[area].link;
			aus[area].title = s[area].title;
	
			//append an element to the legend
			$legend.append("<li id='map-"+area+"'><div><a href='"+aus[area].link+"'>"+aus[area].title+"</a></div></li>");

			//set up a contained environment with events for each area
			;(function (st, area) {
				
				//hover events on the legend
				$("#map-"+area).hover(function(e){
					aus[current].animate({fill: aus[current].color, stroke: "#ccc"}, 500) 
					st.animate({fill: aus[area].hovercolor, stroke: "#000"}, 500);
					$legend.find(".active" ).removeClass("active");
					$(this).addClass("active");
				}, function(e){
					st.animate({fill: aus[area].color, stroke: "#ccc"}, 500);
					$(this).removeClass("active");
				});
				
				st[0].style.cursor = "pointer";
				
				//hover events on the map
				st[0].onmouseover = function () {
					current && aus[current].animate({fill: aus[current].color, stroke: "#ccc"}, 500)  && $("#map-"+current).removeClass("active");
					st.animate({fill: aus[area].hovercolor, stroke: "#000"}, 500);
					R.safari();
					$map.find(".active").removeClass("active");
					$("#map-"+area).addClass("active")
					current = area;
				};
				
				st[0].onmouseout = function () {
					st.animate({fill: aus[area].color, stroke: "#ccc"}, 500);
					$("#map-"+area).removeClass("active")
					R.safari();
				};
				
				//map area is clicked
				$(st[0]).click(function(){
					window.location = aus[area].link;
				});
				
				//initialize by triggering a hover
				st[0].onmouseover();
				st[0].onmouseout();
			})(aus[area], area);
		}
	
		
	}
	
	
}



;(function($) { 
	/**
	 * Calculate width of all [element]s in $(selector);
	 */


	$.fn.calcSubWidth = function(options) {
		
		defaultOptions = {
			el: 'ul',
			rowlength: false
		}

		options = $.extend({},defaultOptions, options);


		var rowWidth = 0;
		//Calculate row 
		$(this).find(options.el).each(function(k,v) {					
			if (k>(options.rowlength-1) && options.rowlength !== false) {
				return;
			}
			rowWidth += $(this).outerWidth(true);
			//max = 4
		});
		
		return rowWidth;
	};


})(jQuery); 


