$(document).ready(function(){

/*===================================================================================
  Get Video Id Passed In From URL
===================================================================================*/
var VideoId = getVideoIdVar()["VideoId"];

function getVideoIdVar() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		vars[key] = value;
	});
	return vars;
}

if (VideoId){
	
	var CleanVideoId = VideoId.replace("#","");
	// alert(CleanVideoId);
	var vidId = $(this).attr("id");
	$.ajax({ 
		url: "../Final_Build/xml/custom.xml", 
		dataType: "xml",
		cache: false,
		error: function(){
				alert('Error: Check the XML document path');
			},
		success: function(xml){
				customXMLFeed(xml);
			}
	});
}
function customXMLFeed(xml){
	//console.log("data",xml);
	var getRootChid =  $(xml).children().get(0).tagName;
	//console.log("getRootChid",getRootChid);
	$(xml).find(getRootChid).children().each(function(r,rootNodes){ 
		if(CleanVideoId == $(rootNodes).attr("id") ) {
			var updated = $(rootNodes).find("updated").text();
			var title = $(rootNodes).find("title").text();
			var desc = $(rootNodes).find("description").text();
			var videoID = $(rootNodes).attr("id");
			var url = 'http://www.youtube.com/v/' + videoID + "?f=user_uploads&app=youtube_gdata";
			var thumb = $(rootNodes).find("thumbnail").attr("url");
			var numViews = $(rootNodes).find("yt_statistics").attr("viewCount");
			var rating = $(rootNodes).find("rating").attr("average");
			
			swfobject.embedSWF('http://www.youtube.com/v/' + videoID + '&rel=1&border=0&fs=1&autoplay=0', 'heroHolder', '926', '470', '9.0.0', false,false, {allowfullscreen: 'true', wmode: 'transparent'});
			$('#videoTitle').html('<a href="'+url+'" target="_blank">'+TruncateText(title,30)+'</a>');
			Cufon.replace('#videoTitle',{hover: true});
			
			var ra = (80 * rating) / 5;
			var raWidth = Math.round(ra);
			$('#videoRealRating').css("width",raWidth);
			$('#videoInfo').html(numViews);
			$('#videoDesc').html(TruncateText(desc, 200));
		
			var nowPlaying = $('#ytList').find('.playing').parent().attr("id");
			$('#ytList').find('.playing').removeClass('playing').attr("src",'img/neverhidefilms/'+nowPlaying+'.jpg');	
			$('#ytList a').each(function(){
				if( $(this).attr('id').match(CleanVideoId) ) {
				   $(this).children("img").attr("src",'img/neverhidefilms/'+CleanVideoId+'-playing.jpg').addClass("playing");
				}
			});	
		}
	}); //getRootChid
}
/*if (VideoId){
	
	var CleanVideoId = VideoId.replace("#","");
	// alert(CleanVideoId);
	
	var vidId = $(this).attr("id");
			//console.log(vidId);
			$(function() {
			    $.getJSON('http://gdata.youtube.com/feeds/api/users/neverhidefilms/uploads/?q='+CleanVideoId+'&alt=json-in-script&callback=?&max-results=1', function(data) { 
			        $.each(data.feed.entry, function(i, item) {
			            var updated = item.updated;
			            var title = item['title']['$t'];
			            var desc = item['media$group']['media$description']['$t'];
			            var url = item['media$group']['media$content'][0]['url'];
			            var thumb = item['media$group']['media$thumbnail'][0]['url'];
			            var numViews = item['yt$statistics']['viewCount'];
			            var rating = item['gd$rating']['average'];
	
			            swfobject.embedSWF(url + '&rel=1&border=0&fs=1&autoplay=0', 'heroHolder', '926', '470', '9.0.0', false,false, {allowfullscreen: 'true', wmode: 'transparent'});
			            
			            $('#videoTitle').html('<a href="'+url+'" target="_blank">'+TruncateText(title,30)+'</a>');
			            Cufon.replace('#videoTitle',{hover: true});
			            
			            var ra = (80 * rating) / 5;
			            var raWidth = Math.round(ra);
			            $('#videoRealRating').css("width",raWidth);
			            $('#videoInfo').html(numViews);
			            $('#videoDesc').html(TruncateText(desc, 200));
			           
			            
			        });
			    });
			});
			if(CleanVideoId == "-prfAENSh2k" || "hUt0RSU9qok") {
				$('#hero').html('<div id="heroHolder"><a target="_blank" href="http://www.youtube.com/watch?v='+CleanVideoId+'"><img src="img/neverhidefilms/error.jpg" alt="Play On YouTube" /></a></div>');
			}
		var nowPlaying = $('#ytList').find('.playing').parent().attr("id");
		$('#ytList').find('.playing').removeClass('playing').attr("src",'img/neverhidefilms/'+nowPlaying+'.jpg');	
		$('#ytList a').each(function(){
	    	if( $(this).attr('id').match(CleanVideoId) ) {
	  	       $(this).children("img").attr("src",'img/neverhidefilms/'+CleanVideoId+'-playing.jpg').addClass("playing");
	  	  	}
	  	});	

		
	
} else {
	$(function() {
	    $.getJSON('http://gdata.youtube.com/feeds/api/users/neverhidefilms/uploads/?q=KMT1FLzEn9I&alt=json-in-script&callback=?&max-results=1', function(data) { 
	        $.each(data.feed.entry, function(i, item) {
	            var updated = item.updated;
	            var title = item['title']['$t'];
	            var desc = item['media$group']['media$description']['$t'];
	            var url = item['media$group']['media$content'][0]['url'];
	            var thumb = item['media$group']['media$thumbnail'][0]['url'];
	            var numViews = item['yt$statistics']['viewCount'];
	            var rating = item['gd$rating']['average'];
	            
	            // alert([url].join('\n')); // display it
	            
	            swfobject.embedSWF(url + '&rel=1&border=0&fs=1&autoplay=0', 'heroHolder', '926', '470', '9.0.0', false,false, {allowfullscreen: 'true', wmode: 'transparent'});
	            $('#videoTitle').html('<a href="'+url+'" target="_blank">'+title+'</a>');
	            Cufon.replace('#videoTitle',{hover: true});
	            
	            var ra = (80 * rating) / 5;
	            var raWidth = Math.round(ra);
	            $('#videoRealRating').css("width",raWidth);
	            $('#videoInfo').html(numViews);
	            $('#videoDesc').html(TruncateText(desc, 200));
	        });
	    });
	});
}*/


/*===================================================================================
  YouTube API Application
===================================================================================*/
$('.thumbContainer a img').hover(function(){
	var parentId = $(this).parent().attr("id");
	$(this).attr("src",'img/neverhidefilms/'+parentId+'-playing.jpg');
		
},function(){
	var parentId = $(this).parent().attr("id");
	if (!($(this).hasClass("playing"))){
		$(this).attr("src",'img/neverhidefilms/'+parentId+'.jpg');
	};
});

function TruncateText(text, len) {
    
    //default value for length to truncate
    if(!len) { len = 50; }
    
    if (text) {
    	var trunc = text;
    	if (trunc.length > len) {
    		trunc = trunc.substring(0, len);
    		trunc = trunc.replace(/\w+$/, '');
    		trunc += '...';
    	}
    }
    
    return trunc;
}


$('.thumbContainer a').click(function(event){
   var vidId = $(this).attr("id");
   if(!$(this).children("img").hasClass('restrict')){
   	//console.log(vidId);
   	$(function() {
   	    $.getJSON('http://gdata.youtube.com/feeds/api/users/neverhidefilms/uploads/?q='+vidId+'&alt=json-in-script&callback=?&max-results=1', function(data) { 
   	        $.each(data.feed.entry, function(i, item) {
   	            var updated = item.updated;
   	            var title = item['title']['$t'];
   	            var desc = item['media$group']['media$description']['$t'];
   	            var url = item['media$group']['media$content'][0]['url'];
   	            var thumb = item['media$group']['media$thumbnail'][0]['url'];
   	            var numViews = item['yt$statistics']['viewCount'];
   	            var rating = item['gd$rating']['average'];
   	            
   	            // alert([title, url, thumb, numViews, rating].join('\n')); // display it

   	            swfobject.embedSWF(url + '&rel=1&border=0&fs=1&autoplay=0', 'heroHolder', '926', '470', '9.0.0', false,false, {allowfullscreen: 'true', wmode: 'transparent'});
   	            
   	            $('#videoTitle').html('<a href="'+url+'" target="_blank">'+TruncateText(title,30)+'</a>');
   	            Cufon.replace('#videoTitle',{hover: true});
   	            
   	            var ra = (80 * rating) / 5;
   	            var raWidth = Math.round(ra);
   	            $('#videoRealRating').css("width",raWidth);
   	            $('#videoInfo').html(numViews);
   	            $('#videoDesc').html(TruncateText(desc, 200));
   	           
   	            
   	        });
   	    });
   	});
   }
   else {
   	if(vidId == "-prfAENSh2k" || "hUt0RSU9qok") {
   		var vidId = $(this).attr("id");
   		$('#hero').html('<div id="heroHolder"><a target="_blank" href="http://www.youtube.com/watch?v='+vidId+'"><img src="img/neverhidefilms/error.jpg" alt="Play On YouTube" /></a></div>');
   	}
   }
   var nowPlaying = $('#ytList').find('.playing').parent().attr("id");
   $('#ytList').find('.playing').removeClass('playing').attr("src",'img/neverhidefilms/'+nowPlaying+'.jpg');	
   $(this).children("img").attr("src",'img/neverhidefilms/'+vidId+'-playing.jpg').addClass("playing");
   // console.log(vidId);
});


/*===================================================================================
  PNG Fix
===================================================================================*/
$(document).pngFix();
$('#topNav').pngFix();
$('#header').pngFix();
$('#register').pngFix();

/*===================================================================================
  Global Nav
===================================================================================*/
	$('#globalNav li').hover(function() {
		$(this).children('ul').fadeIn(50);
	}, function() {
		$(this).children('ul').fadeOut(50);
	});

/*===================================================================================
  Auto Fill Search
===================================================================================*/
	autoFill($(".searchField"), "SEARCH");
    
    function autoFill(id, v){
		$(id).attr({ value: v }).focus(function(){
	    	if($(this).val()==v){
	    		$(this).val("");
	    	}
	    }).blur(function(){
	    	if($(this).val()==""){
	    		$(this).val(v);
	    	}
	    });
	    
	}

$('.footerLeft').hover(function() {
	$('#langSelectionMenu').fadeIn(50);
},function(){
	$('#langSelectionMenu').fadeOut(50);
});

/*===================================================================================
  Drag Bar for Never Hide Films
===================================================================================*/
	
       sc = $('#ytList');
       sch = 1255;
       containerW = 591;
       $('.dragBar').draggable({
           axis: 'x',
           containment: 'parent',
           drag: function(event, ui) {
               var move = sch - containerW;
               var pos = $('.dragBar').css("left").replace("px","");
               sc.css('left',- pos/containerW*move + "px")
           }
		});
		
/*===================================================================================
  Drag Bar for Rare Prints
===================================================================================*/
/*	
       rc = $('#rpList');
       rch = 960;
       //containerWrp = 300;
       containerWrp = $(rc).hasClass('aviatorsightings') ? 400 : 239;
       $('.rareprints .dragBar').draggable({
           axis: 'x',
           containment: 'parent',
           drag: function(event, ui) {
               var rpmove = rch - containerWrp;
               var rppos = $('.dragBar').css("left").replace("px","");
               rc.css('left',- rppos/containerWrp*rpmove + "px")
           }
		});
 */
    
       rc = $('#rpList');
       rch = $('#targetTab').width();
       
       var max_slide = $('.rareprints .rpSlider').width() - $('.rareprints .dragBar').width();
       var offset = $('.rpThumbs').width();
       
       $('.rareprints .dragBar').draggable({
           axis: 'x',
           containment: 'parent',
           drag: function(event, ui) {
               var rppos = $('.dragBar').css("left").replace("px","");               
               rc.css('left',- ((rppos/max_slide*rch) - (rppos/max_slide*offset)) + "px")
           }
		});
  
		window.updateSliderVars = function() {
			max_slide = $('.rareprints .rpSlider').width() - $('.rareprints .dragBar').width();
			rch = $('#targetTab').width();
			offset = $('.rpThumbs').width();
		}    

/*===================================================================================
  Hot Spot Div
===================================================================================*/
    $("div.clickDiv").click(function(){
		window.location = $(this).attr("url");
		return false;
	});

});


/*===================================================================================
  Legal Menu
===================================================================================*/

function initMenus() {
	$('ul.menu ul').hide();
	$.each($('ul.menu'), function(){
		$('#' + this.id + '.expandfirst ul:first').show();
	});
	$('ul.menu li a').click(
		function() {
			var checkElement = $(this).next();
			var parent = this.parentNode.parentNode.id;

			if($('#' + parent).hasClass('noaccordion')) {
				$(this).next().slideToggle('normal');
				return false;
			}
			if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
				if($('#' + parent).hasClass('collapsible')) {
					$('#' + parent + ' ul:visible').slideUp('normal');
				}
				return false;
			}
			if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
				$('#' + parent + ' ul:visible').slideUp('normal');
				checkElement.slideDown('normal');
				return false;
			}
		}
	);
}
$(document).ready(function() {initMenus();});

/*===================================================================================
  Search Results
===================================================================================*/
$('.pagination a').each(function() {
	$(this).addClass($(this).text());
});

$('.pagination a').click(function() {
	$('.pagination').find("." +  $(this).text()).addClass("active").parent().siblings().find('a').removeClass("active");
});

/*===================================================================================
  Forgot Password Show/Hide
===================================================================================*/
$('#forgotPwd').click(function() {
	$('.forgotEmail').show();
});

/*

CUSTOM FORM ELEMENTS

Created by Ryan Fait
www.ryanfait.com

The only thing you need to change in this file is the following
variables: checkboxHeight, radioHeight and selectWidth.

Replace the first two numbers with the height of the checkbox and
radio button. The actual height of both the checkbox and radio
images should be 4 times the height of these two variables. The
selectWidth value should be the width of your select list image.

You may need to adjust your images a bit if there is a slight
vertical movement during the different stages of the button
activation.

Visit http://ryanfait.com/ for more information.

*/

var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "75";
var longSelectWidth = "252";

/* No need to change anything after this */

document.write('<style type="text/css">input.styled { display: none; } select.styled { margin: 0; position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0);}select.longStyled { margin: 0; padding: 3px 0; position: relative; width: ' + longSelectWidth + 'px; opacity: 0; filter: alpha(opacity=0);}</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled" || inputs[a].className == "longStyled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				span[a].onmousedown = Custom.pushed;
				span[a].onmouseup = Custom.check;
				document.onmouseup = Custom.clear;
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.choose;
			}
			else if(inputs[a].className == "longStyled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "longSelect";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.choose;
			}
		}
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}
window.onload = Custom.init;

