/**
 * @author Jeremy.Manoto
 */
$(document).ready(function() {    

    DiFR_Init();

    Splash_Init();

    Calendar_Init();

    Logo_Init();

    IE6PNGFIX();

    Navigation_Init();

    MoreInfo_Init();

    ENews_Init();

    News_Init();

    Testing_Init();

    Search_Init();

});

//Cross domain tracking script
function InitializeLinks() {

    $("a").each(
       function Check() {
           if ($(this)[0].href.indexOf("tickets.musicaviva.com") >= 0) {
               
               var linkHref = $(this).attr("href");

               var gaTracker = _gat._createTracker("UA-10257298-1");
               gaTracker._setDomainName('musicaviva.com.au');
               gaTracker._setAllowLinker(true);
               gaTracker._setAllowHash(false);
               gaTracker._addIgnoredRef('musicaviva.com.au');
               gaTracker._addIgnoredRef('tickets.musicaviva.com.au');

               var linkerUrl = gaTracker._getLinkerUrl(linkHref);
               $(this).attr("href", linkerUrl);
           }

       });       
};
    

	/**
	 * Splash page IEFixes
	 */
	function Splash_Init() {
		$(".splash .left").hover(function() {
			$(this).css("cursor", "pointer");
		}, function() {
			
		})
	}



	function Logo_Init() {
		$("h1#logo, #footer h2").click(function() {
			window.location = (VirtualDirectory == "") ? "/" : VirtualDirectory;
		})
	}

	/** 
	 * Fix IE PNGs
	 */
	function IE6PNGFIX() {
		$.ifixpng(VirtualDirectory + '/images/pixel.gif'); 
		
		var fixableElements = "h1, h5, #subnav a, .curve, .box .footer, .box .header, .box3 .footer, .box6.large .header, .box6.large .footer, .box6 .footer.expand, .box6 h5, .button, .box6.download, .splash .splash-concerts, .splash .splash-education, .aiming-to-inspire";
		//$(fixableElements).ifixpng();
		
		if ($.browser.msie && $.browser.version == "6.0") {
			//DD_belatedPNG.fix(fixableElements);
		}
			
		$(fixableElements).ifixpng();
		
		$(".fixpng").toggle(function() {
			//alert("Fixing PNGs");
			//$("h5, .box .footer, .box .header, .box3 .footer").ifixpng().css({ border: '1px solid red'});
			$(fixableElements).ifixpng();
			//$("h2, h3, h4, h5").find("img").ifixpng();
		}, function() {
			//alert("Un Fixing PNGs");
			$("h5, .box .footer, .box .header, .box3 .footer").iunfixpng().css({border: 'none'});
			
		}).hide();
		
	}



	/**
	 * Navigation Initialization
	 */
	function Navigation_Init() {
		$("div#nav ul")
			.supersubs({ minWidth: 15, maxWidth: 27, extraWidth: 3 })
			.superfish({ pathClass: 'current', dropShadows: false, autoArrows: false, delay: 400, hoverClass: 'hover'});
		
		if (!$.browser.msie) {
			$("#quickmenu ul").supersubs({
				minWidth: 15,
				maxWidth: 27,
				extraWidth: 3
			}).superfish({
				pathClass: 'current',
				dropShadows: false,
				autoArrows: false,
				delay: 400,
				hoverClass: 'hover'
			});
		} else {
		    $("#quickmenu").css({overflow: "hidden", height: "36px"});
		}
		
		
		// Adjust z-index
		$("div#nav ul>li").each(function(index, li) {
			li = $(this);
			//alert(300 + index);
			li.css({ 'z-index': (300 - index) });
		});
		
		if ($.browser.safari) {
			//$("#nav ul a").css({ padding: "10px 12px 14px !important"});
			
			$("div#nav").hover(function(){
				$("div.VimeoHolder").css({"height":"308px"});
				$("div.VimeoHolderInner").css({"display":"none"});
			}, function(){
				$("div.VimeoHolderInner").css({"display":"block"});
			})
			
		}
		
		//Adjust background of 1st item
		//$("div#nav>ul>li:first, div#quickmenu>ul>li:first").css({'background-position': '-2px 0px'});
		$("div#subnav>ul>li:first").css({'border-top': 'none'});

		
		
		
	}

	
	/**
	 * Scan through content for 'more info' links and apply appropriate style
	 */
	function MoreInfo_Init() {
		$('a').each(function() {
			if ($(this).html().toUpperCase() == "MORE INFO") {
				$(this).addClass("more-info");
			}
		});
		//$("a:contains('more info')").addClass("more-info");
	}

	
	/**
	 * Apply Image Replacements for headings
	 */
	function DiFR_Init() {
		
		var isDark = $("body").hasClass("dark");
		
		var DiFRPath = VirtualDirectory + "/services/fontImageReplace.ashx";
		
		
		$("h2.difr").each(function() {
			var h2 = $(this);
			var text = h2.html();
			var config = (isDark) ? "H2_DARK" : "H2";
			//Convert to uppercase
			var textUpper = text; //.toUpperCase();

			var imgSource = DiFRPath + "?config=" + config + "&text=" + encodeURIComponent(textUpper);
			
			h2.empty();
			var img = new Image();
			img.src = imgSource;
			h2.append($(img));
			
			var span = "<span>" + text + "</span>"
			h2.append(span);

			
			runOnLoad(function(){
				h2.children("img").ifixpng();
				if ($.browser.msie && $.browser.version == "6.0") {
					h2.find("img").css({
						height: img.height + "px",
						width: "100%"
					});
				}
			});
			
		});
		
		$("h3.difr").each(function() {
			var h3 = $(this);
			var text = h3.html();
			var config = (isDark) ? "H3_DARK" : "H3";
			
			//Convert to uppercase
			var textUpper = text; //.toUpperCase();
			//alert("H3 Text: "  +escape(textUpper));
			var imgSource = DiFRPath + "?config=" + config + "&text=" + encodeURIComponent(textUpper);
			
			h3.empty();
			var img = new Image();
			img.src = imgSource;
			h3.append($(img));
			
			var span = "<span>" + text + "</span>"
			h3.append(span);
			
			runOnLoad(function(){
				h3.children("img").ifixpng();
				if ($.browser.msie && $.browser.version == "6.0") {
					h3.find("img").css({
						height: img.height + "px",
						width: "100%"
					});
				}
			});
		});
		
		
		
		$("h4.difr").each(function() {
			var h4 = $(this);
			var text = h4.html();
			var config = (isDark) ? "H4_DARK" : "H4";
			
			//Convert to uppercase
			var textUpper = text; //.toUpperCase();
			var imgSource = DiFRPath + "?config=" + config + "&text=" + encodeURIComponent(textUpper);
			
			h4.empty();
			var img = new Image();
			img.src = imgSource;
			h4.append($(img));
			
			var span = "<span>" + text + "</span>"
			h4.append(span);
			
			runOnLoad(function(){
				h4.children("img").ifixpng();
				if ($.browser.msie && $.browser.version == "6.0") {
					h4.find("img").css({
						height: img.height + "px",
						width: "100%"
					});
				}
			});
		});
		
		$("h6.difr").each(function() {
			var h6 = $(this);
			var text = h6.html();
			text = unescape(text);
			
			var config = (isDark) ? "BOXH6_DARK" : "BOXH6";
			
			//Convert to uppercase
			var textUpper = text; //.toUpperCase();
			var imgSource = DiFRPath + "?config=" + config + "&text=" + encodeURIComponent(textUpper);
			var ir = "<img src='" + imgSource + "' border='0' alt='" + text + "' />";

			h6.empty();
			var img = new Image();
			img.src = imgSource;
			h6.append($(img));
			
			var span = "<span>" + text + "</span>"
			h6.append(span);
			
			runOnLoad(function(){
				h6.children("img").ifixpng();
				if ($.browser.msie && $.browser.version == "6.0") {
					h6.find("img").css({
						height: img.height + "px",
						width: "100%"
					});
				}
			});
		});
		
		
		$(".reviews q").each(function() {
			var quote = $(this);
			var text = quote.html();
			var cite = quote.attr("title");
			var config = (isDark) ? "QUOTE_DARK" : "QUOTE";
			var configCite = (isDark) ? "CITE_DARK" : "QUOTESOURCE";
			
			cite = cite.toUpperCase();
			
			var ir = "<img src='" + DiFRPath + "?config=" + config + "&text=" + encodeURIComponent(text) + "' border='0' alt='" + text + "' />";
			var irCite = "<img src='" + DiFRPath + "?config=" + configCite + "&text=" + encodeURIComponent(cite) + "' border='0' alt='" + cite + "' />";
			var span = "<span>" + text + "</span>";
			
			quote.html(ir + "<br>" + span + irCite);
			
			runOnLoad(function(){
				quote.children("img").ifixpng();
			});
		})

	}
	
	
	
	/**
	 * News Listing Expand/Contract
	 */
	function News_Init() {
		$(".news .footer .more.button").click(function() {
			var button = $(this);
			var fullArticle = button.parent().prev().find(".full-article");
			
			fullArticle.slideToggle("slow");
			
			if (button.hasClass("close")) {
				button.removeClass("close");
			} else {
				button.addClass("close");
			}
		
		});
	}
	
	
	/**
	 * Calendar Initialization
	 * There should only be 1 (ONE) calendar object on a page.
	 * HOWEVER, there CAN be many calendar triggers!! 
	 */
	var calendar;
	function Calendar_Init() {
		
		//Check for required calendar markup in page.
		var body = $(body); 
		if (body.find("#calendar").length == 0) {
			//Doesn't exist. Add the markup
			
			$.get(VirtualDirectory + "/templates/Calendar.html", function(data) {
				data = $(data);
				data.appendTo("body");
				calendar = new Calendar($(".scroll-calendar"));
			});
		} else {
			calendar = new Calendar($(".scroll-calendar"));
		}
		
		CalendarOverlay_Init();

	}
	

	/**
	 * Perfomers an Artist/Performer search with the backend
	 * @param {Object} state
	 * @param {Object} region
	 * @param {Object} program
	 */
	function MVA_PerformerSearch(state, region, program) {
	
		
		var PostUrl = VirtualDirectory + "/services/ArtistSearch.ashx";
		var PostParams = { 'a': 'search', 'state': state, 'region': region, 'program': program };

		$.get(PostUrl, PostParams, function(data) {
		    var searchResults = $(".performer-search .results");
		    var searchNoResults = $(".performer-search .no-results");
		    var artists = eval(data);

			$(".performer-search").find(".artist-state").html(state);

		    // Remove previous results;
		    searchResults.empty();

		    // Loop through and the get new results
		    if (artists.length > 0) {
		        searchNoResults.hide();
		        searchResults.show();
		        for (var a in artists) {
		            if (artists[a].artist_id != undefined) {
		                var artistID = parseInt(artists[a].artist_id);

		                //Get the artists html
		                var artistHtml;

		                var PostUrl = VirtualDirectory + "/services/RenderModuletemplate.ashx";
		                var PostParams = {
		                    moduletemplate_id: 47,
		                    instance_id: artistID
		                };

		                $.get(PostUrl, PostParams, function(data) {
		                    artistHtml = $(data);
		                    

		                    if (searchResults.find(".artist_" + artistID).length == 0) {
								
		                        searchResults.append(artistHtml);
		                    }

		                    searchResults.find(".artist_" + artistID).fadeIn().ifixpng();
		                    searchResults.find("h5, .footer").ifixpng();

		                });

		            }

		        }
		    } else {
		        // Show No Results div
		        searchNoResults.show();
		        searchResults.hide();
		    }
		});
	}
	
	
	/**
	 * Gets the html to list a specified artist
	 * @param {Object} artistID to show
	 */
	function RenderArtist(artistID) {
		var PostUrl = VirtualDirectory + "/services/RenderModuletemplate.ashx";
		var PostParams = { moduletemplate_id: 47, instance_id: artistID };
		
		var html;
		$.get(PostUrl, PostParams, function(data) {
			html = data;
		});
	}
	
	
	
	/**
	 * 
	 */
	function ENews_Init() {

		
	}
	

	
	/************************************************************************************
	 * Testing features
	 */
	function Testing_Init() {
		
		$(".scroll-calendar #txtDate").val(Date.today().toString("yyyy-MM-dd H:mm"))
		
		//Generate Performances
		$(".scroll-calendar .generate-performances").click(function() {
			var minDate = Date.parse("2003-01-01");
			var maxDate = Date.parse("2009-12-31");
			var performance;
			for (i = 1; i <= 100; i++) {
				//alert(GenerateRandomDate(minDate, maxDate))
				var date = GenerateRandomDate(minDate, maxDate).toString("yyyy-MM-dd hh:mm");
				
				performance = new DetailItem("Performance " + i, "Melbourne", "Melbourne Arts Centre", date, "images/performance/cal/sample1.jpg", "http://www.google.com");
				calendar.addDetailItem(performance);
			}
			//calendar.sortDetailItems();
		});
		
		var timeOut;
		$(".scroll-calendar .add-performance").click(function() {
			var name = $(".scroll-calendar #txtPerformanceName").val();
			var date = $(".scroll-calendar #txtDate").val();
			var performance = new DetailItem(name, "Melbourne", "Melbourne Arts Centre", date, "images/performance/cal/sample1.jpg", "http://www.google.com" );
			calendar.addDetailItem(performance);
			timeOut = setTimeout(function(){
				//alert(nullable)
			}, 1);
		}).hover(function() {
			$(this).css({ cursor: "pointer", fontWeight: "bold"});
		}, function() {
			$(this).css({ cursor: "default", fontWeight: "normal"});
		});
		

	}
	
	
	function GenerateRandomDate(minDate, maxDate) {
		var minYear = parseInt(minDate.toString("yyyy"));
		var minMonth = parseInt(minDate.toString("M"));
		var maxYear = parseInt(maxDate.toString("yyyy"));
		var maxMonth = parseInt(maxDate.toString("M"));
		
		var random = Math.random();
		var random2 = Math.random();
		var year = Math.floor(random * (maxYear-minYear + 1) + minYear);
		var month = Math.floor(random2 * (maxMonth-minMonth + 1) + minMonth);
		var day = Math.floor(random * (28-1 + 1) + 1);
		var hour = Math.floor(random2 * (23-0 + 1) + 0);
		var minutes = Math.floor(random * (59-0 + 1) + 0);
		
		var date = Date.parse(year + "-" + month + "-" + day + " " + padout(hour) + ":" + padout(minutes));
		if (date == null) {
			alert(year + "-" + month + "-" + day + " " + hour + ":" + minutes);
		}
		return date;
		
	}

	function padout(number) { return (number < 10) ? '0' + number : number; }

	function ShowSchoolBookingForm(dateRange, artistID) {
	    //redirect to booking form
	    window.location.href = ((VirtualDirectory == "") ? "/" : (VirtualDirectory + '/')) + "education/booking?a=" + artistID + "&d=" + dateRange;
	}

	function Search_Init() {
	    $("#searchBox a").click(function() {
	        var searchString = $("#txtSearchBox").val();
	        window.location = VirtualDirectory + "/search?q=" + searchString;
	        return false;
	    });

	    $("#txtSearchBox").keyup(function(e) {
	        if (e.keyCode == 13) {
	            $("#searchBox a").click();
	        }
	    });

	}

	

