function setHash(hash) {
	window.location.hash = hash;
	return;
	if (navigator.userAgent.match(/Safari/i)) {
		if (parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Safari') + 7)) < 412) {
			// the form doesn't need to be attached to the document.
			var f = document.createElement('form');
			f.action = hash;
			f.submit();
		} else {
			var evt = document.createEvent('MouseEvents');
			evt.initEvent('click', true, true);
			var anchor = document.createElement('a');
			anchor.href = hash;
			anchor.dispatchEvent(evt);
//			window.location.reload();
		}
	} else {
		window.location.hash = hash;
	}
}

function callback(hash)
{
	hash = window.location.hash;
	if (hash == "") {
		showMain();
	}
	else if (hash == "#watchEducationalDVDs") {
		showEducationalDVDs();
	}
	else if (hash.indexOf("#watchEducationalDVD-") != -1) {
		showEducationalDVD(hash.split("-")[1]);
	}
}

var educationalDVDs = new Array("race","drugs","family","sex","character","immigration");

function showMain() {
	$("#movieInfoWrapper").show();
	$("#movieInfoWrapper #movieInfo").hide();
	$("#educationalDVDInfoWrapper").hide();
	
	$("#moviesMain #movieSections").show();
	$("#moviesMain #dvdMovies").hide();
	$("#moviesMain").show();
	$("#watchEducationalDVDs li.buyNow").hide();
	$(".fullMovieSection").hide();
	$("#backButton").css("visibility","hidden");
	$("#watchEducationalDVDs img").attr("src","/flv/educational_dvd.jpg");
	
	$("#watchEducationalDVDs").unbind("mouseover");
	
	$("#watchEducationalDVDs").mouseover(function() {
		$("#movieInfoWrapper #movieInfo").hide();
		$("#educationalDVDInfoWrapper").show();
		$("#educationalDVDInfoWrapper h3").hide();
		$("#educationalDVDInfo").css("display","table");
		
		$("#educationalDVDInfo img").attr("src","/flv/educational_dvd_small.jpg");
		$("#educationalDVDInfo #dvdTitle").html( "Educational DVDs" );
		$("#educationalDVDInfo #dvdDescription").html( "Six DVD's containing Reel Works' best award winning short films collected by topic: Race, Drugs, Family, Sex & Relationships, Identity and the Immigrant experience. Personal stories, powerfully told by teens, for teens." );
	});
}

function showEducationalDVDs() {
	$("#moviesMain").hide();
	$(".fullMovieSection").show();
	$("#backButton").css("visibility","visible");
	$("#movieInfoWrapper").hide();
	$("#educationalDVDInfoWrapper").show();
	$("#educationalDVDInfoWrapper h3").show();
	$("#educationalDVDInfo").hide();
}

function showEducationalDVD(educationalDVD) {
	$("#watchEducationalDVDs").unbind("mouseover");
	getDVDMovies(educationalDVD.charAt(0).toUpperCase() + educationalDVD.substr(1));
	$("#movieInfoWrapper").show();
	$("#movieInfoWrapper #movieInfo").hide();
	$("#educationalDVDInfoWrapper").show();
	$("#educationalDVDInfoWrapper h3").hide();
	prepareEducationalDVD( $(".watchEducationalDVDs dl dt:contains('" + educationalDVD + "') img.small").eq(0) );
}

function prepareEducationalDVD( refEducationalDVD ) {
	thisDT = refEducationalDVD.parent();
	$("#educationalDVDInfo:hidden").each(function() {
		$("#educationalDVDInfo").css("display","table");
	});
	$("#educationalDVDInfo img").attr("src",thisDT.find("img").attr("src"));
	$("#watchEducationalDVDs li.buyNow").show();
	$("#watchEducationalDVDs li.buyNow").unbind();
	$("#watchEducationalDVDs li.buyNow").click(function() {
		window.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2779712&item_name=" + "Educational DVD - " + thisDT.nextAll("dd").eq(0).text());
	});
	$("#watchEducationalDVDs li img").attr("src",thisDT.find("img").attr("src").replace("_small",""));
	$("#educationalDVDInfo #dvdTitle").html( thisDT.nextAll("dd").eq(0).html() );
	$("#educationalDVDInfo #dvdDescription").html( thisDT.nextAll("dd").eq(1).html() );
}

$(document).ready(function() {
	setupSection("new releases", "watchNewReleases");
	//setupSection("featured", "watchFeatured");
	setupSection("award winners", "watchAwardWinners");

	$("#watchEducationalDVDs").click(function() {
		setHash("#watchEducationalDVDs");
	});
	$("#backButton").click(function() {
		showMain();
	});
	$(".watchEducationalDVDs dl dt").click(function() {
		var educationalDVD = $(this).find("span.hidden").text();
		setHash("#watchEducationalDVD-" + educationalDVD);
	});
	$(".watchEducationalDVDs dl dt img.small").mouseover(function() {
		prepareEducationalDVD( $(this) );
	});
	$(".watchEducationalDVDs dl dt span.buy").click(function() {
		window.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2779712&item_name=" + "Educational DVD - " + $(this).parent().nextAll("dd").eq(0).text());
	});
	
    $.history.init(callback);
    $("a[@rel='history']").click(function(){
        $.history.load(this.href.replace(/^.*#/, ''));
        return false;
    });
});

function setupSection(section, sectionEle) {
	$.get("/admin/functions_new.php?fn=Get XML2&abc=1&section=" + section, function (data, textStatus) {
		$(data).find("movies movie").each(function(i) {
			thisData = $(this);
			thisMovie = $("#watchTemplate").clone().removeAttr("id");
			if (i%2 == 0)
				thisMovie.css("clear","both");
			thisMovie.find("dl dt img").each(function() {
				loadImage(thisData.attr("pic"), $(this), thisData, function(thisImage, thisData) {
					setupHover(thisImage, thisData);
//					thisImage.css("display","none");
//					setupHover( $(".movieSection li dl img"), thisData );
				});
			});
			thisMovie.find(".movieTitle").html(
				urldecode(thisData.attr("title"))
			);
			keywords = urldecode( thisData.attr("keywords") ).toLowerCase();
			var educationalDVD;
			for (j=0; j<educationalDVDs.length; j++) {
				if (keywords.indexOf(educationalDVDs[j]) != -1) {
					educationalDVD = educationalDVDs[j];
				}
			}
			if (educationalDVD != undefined) {
				thisMovie.find(".movieOptions span.buy:eq(1), .movieOptions span.separator").css("display","inline");
				thisMovie.find(".movieOptions span.buy").eq(1).click(function() {
					$(".watchEducationalDVDs dl dt:contains('" + educationalDVD + "') img.small").each(function() {
						thisDT = $(this).parent();
						window.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2779712&item_name=" + "Educational DVD - " + escape(thisDT.nextAll("dd").eq(0).text()));
					});
				});
			}
			else {
				thisMovie.find(".movieOptions span.buy:eq(0), .movieOptions span.separator").css("display","inline");
				setupBuyClick(thisMovie, thisData);
//				thisMovie.find("dl dd span.buy a").click(function() {
//					alert("yay");
//					$("#buyMovie dl dd.class").text(
//						urldecode(thisData.attr("class"))
//					);
//					window.open("");
//					window.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2779712&item_name=" + "Educational DVD - " + $(this).parent().nextAll("dd").eq(0).text());
//				});
			}
			/*
			thisMovie.find("dl dd span.buy").click(function() {
				window.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2779712&item_name=" + "Educational DVD - " + $(this).parent().nextAll("dd").eq(0).text());
			});
			*/
			loadFLVData(thisData.attr("filename_full_movie"), thisMovie, thisData);
			$("#" + sectionEle).append(thisMovie).css("display","none").css("display","list-item");
		});
		tb_init('a.thickbox, area.thickbox, input.thickbox');
//		setupHover( $(".movieSection li dl img"), thisData );
	});
}

function getDVDMovies(keyword) {
	$("#watchDVDMovies li[class!='title']").remove();
	$("#watchDVDMovies li h2").text(keyword);
	$.get("/admin/functions_new.php?fn=Get XML2&abc=1&searchBy=keywords&searchQuery=" + keyword, function (data, textStatus) {
		$(data).find("movies movie").each(function(i) {
			thisData = $(this);
			thisMovie = $("#watchTemplate").clone().removeAttr("id");
			if (i%4 == 0)
				thisMovie.css("clear","both");
			thisMovie.find("dl dt img").each(function() {
				loadImage(thisData.attr("pic"), $(this), thisData, function(thisImage, thisData) {
					setupHover(thisImage, thisData);
//					thisImage.css("display","none");
//					setupHover( $(".movieSection li dl img"), thisData );
				});
			});
			thisMovie.find(".movieTitle").html(
				urldecode(thisData.attr("title"))
			);
			educationalDVD = keyword.toLowerCase();
//			thisMovie.find(".movieOptions span.buy, .movieOptions span.separator").css("display","inline");
//			thisMovie.find(".movieOptions span.buy").click(function() {
			thisMovie.find(".movieOptions span.buy:eq(1), .movieOptions span.separator").css("display","inline");
			thisMovie.find(".movieOptions span.buy").eq(1).click(function() {
				$(".watchEducationalDVDs dl dt:contains('" + educationalDVD + "') img.small").each(function() {
					thisDT = $(this).parent();
					window.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2779712&item_name=" + "Educational DVD - " + escape(thisDT.nextAll("dd").eq(0).text()));
				});
			});
			loadFLVData(thisData.attr("filename_full_movie"), thisMovie, thisData);
			$("#watchDVDMovies").append(thisMovie).css("display","none").css("display","list-item");
		});
	});
	$(".fullMovieSection").hide();
	$("#moviesMain #movieSections").hide();
	$("#moviesMain #dvdMovies").show();
	$("#moviesMain").show();
}

function loadImage(abcx, thisImage, thisData, callback) {
	if (abcx != undefined) {
		$.get("/admin/functions_new.php?abcx=" + abcx, function(picData, picTextStatus) {
			if (picData == "1")
				thisImage.attr("src", "/flv/" + abcx);
			else
				thisImage.attr("src", "/pics/coming_soon.jpg");
			if (callback!=undefined)
				callback(thisImage, thisData);
		});
	}
	else {
		thisImage.attr("src", "/pics/coming_soon.jpg");
	}
}

function loadFLVData(abcx, thisMovie, thisData) {
	if (thisData.attr("filename_full_movie") != undefined) {
		$.get("/admin/functions_new.php?abcx=" + abcx, function(flvData, flvTextStatus) {
			if (flvData == 1) {
				thisWatch = thisMovie.find(".movieOptions span.watch");
				thisWatch.css("color","#BFBFBF");
				thisWatch.click(function() {
					window.open("http://www.reelworks.org/watch2.php?" +
								"classs=" + thisData.attr("class") +
								"&title=" + thisData.attr("title") +
								"&filmer=" + thisData.attr("filmer") +
								"&fName=" + thisData.attr("filename_full_movie"));
				});
			}
			else
				thisMovie.find(".movieOptions span.watch").attr("dis","true");
				
			thisMovie.find("span[class!='separator'][dis!='true']").hover(
				function() {
					$(this).css("color","#BFBF00");
				},function() {
					$(this).css("color","#BFBFBF");
				}
			);
		//css("color","#FFFFFF");
//			if (loadFLVData == "1")
//				document.title = thisMovie.get(0);
//				thisFLV.attr("src", thisFLV.attr("src") + thisData.attr("pic"));
//			else
//				thisFLV.attr("src", "/pics/coming_soon.jpg");
		});
	
	}
	else {
//		thisImage.attr("src", "/pics/coming_soon.jpg");
	}
}

function setupHover(ele, thisData) {
	ele.hover(
		function() {
			thisMovie = $(this).parent().parent();
			$(this).parent().parent().css("opacity",".5");
			
//			$("#educationalDVDInfoWrapper").hide();
			$("#movieInfo").hide();
//			$("#movies").get(0).scrollIntoView();
//			document.title = $("#movieInfo").height();
			$("#movieInfo dd.film").html( urldecode(thisData.attr("title")) );
			$("#movieInfo dd.filmMaker").html( urldecode(thisData.attr("filmer")) );
			$("#movieInfo dd.class").html( urldecode(thisData.attr("class")) );
			$("#movieInfo dd.description").html( urldecode(thisData.attr("description")) );
			$("#movieInfo img").attr("src",thisMovie.find("img").attr("src"));
			$("#movieInfo:hidden").css("display","table");
			
//			if ($("#movieInfo").css("visibility") == "hidden") {
//				$("#movieInfo").slideDown(1000,function(){
//					$("#movieInfo").css("display","table");
//				});
//			}
		},
		function() {
			thisMovie = $(this).parent().parent();
			thisMovie.css("opacity","1");
		}
	);
}

function setupBuyClick(thisMovie, thisData) {
	if (thisData.attr("class") == "")
		thisMovie.find(".movieOptions span.buy:eq(0), .movieOptions span.separator").css("display","none");
	thisMovie.find(".movieOptions span.buy:eq(0) a").click(function() {
		$("dl#buyMovie dd.class").html(
			urldecode(thisData.attr("class"))
		);
		$("dl#buyMovie dd.individuals a").attr(
			"href", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2780196&os0=for Individuals" +
				"&item_name=" + urldecode(thisData.attr("class")) + " Class DVD (includes \"" + urldecode(thisData.attr("title")) + "\")"
		);
		$("dl#buyMovie dd.communityOrgs a").attr(
			"href", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2780196&os0=for Community Organizations, High Schools, and Non-Profits" +
				"&item_name=" + urldecode(thisData.attr("class")) + " Class DVD (includes \"" + urldecode(thisData.attr("title")) + "\")"
		);
		$("dl#buyMovie dd.commercialOrgs a").attr(
			"href", "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2780196&os0=for Institutions, Universities, and Commercial Organizations" +
				"&item_name=" + urldecode(thisData.attr("class")) + " Class DVD (includes \"" + urldecode(thisData.attr("title")) + "\")"
		);
	});
}

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {};
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    try {
	    ret = decodeURIComponent(unescape(ret));
    }
    catch(e) {
	    ret = decodeURIComponent(unescape(ret));
    }
 
    return ret;
}