/* CCGallery - HTML5 Multimedia Gallery 
 * Copyright 2011, Nilok Bose  
 * http://codecanyon.net/user/cosmocoder
*/

jQuery(function($){
var myint;
var webroot='http://www.vidcano.com/';
var siteroot='';
var okaytoreg=true;
var okaytoreg2=true;


var $oinfo,
		    $oextras,
			$orent,
			$otitle2,
			$ofirstimg,
			$odescription,
			$otitle,
			$mask,
			$overlayLoader,
			$overlay,
			$overlayContent,
            $playerFirstImg,
			$playerText1,
			$playerTitle,
			$playerRent,
			$playerExtras,
			$upperContent,
			$close,
			meplayer,
			$win;
		

		
		
		function addoverlaydivs(){
		
		    $mask = $('<div id="mask" style="display:none;"/>').appendTo('body');
			$overlayLoader = $('<div id="overlayLoader" style="display:none;"/>').appendTo('body');
			$overlay = $('<div id="overlay" style="display:none;"/>').appendTo('body');
			$overlayContent = $('<div id="overlayContent"/>').appendTo($overlay);
            $playerFirstImg = $('<div id="playerFirstImg"/>').appendTo($overlay);
			$playerText1 = $('<div id="playerText1"/>').appendTo($overlay);
			
			$playerTitle = $('<div id="playerTitle"/>').appendTo($overlay);
			$playerRent = $('<div id="playerRent"/>').appendTo($overlay);
			$playerExtras = $('<div id="playerExtras"/>').appendTo($overlay);
			$upperContent = $('<div id="upperContent"/>').appendTo($overlay);
			$close = $('<a id="close"/>').appendTo($overlay);
			$win = $(window);
			
		$upperContent.html('<h3></h3>');
		$playerTitle.html('<h3></h3>');
		$playerFirstImg.html('<span></span>');
		$playerText1.html('<p></p>');
		$playerRent.html('<p></p>');
		$playerExtras.html('<p></p>');
		$overlayContent.html('<div class="details"><h2></h2><p></p></div>');
		
		$otitle = $upperContent.find('h3');
			$odescription = $overlayContent.find('p');
		   $ofirstimg = $playerFirstImg.find('span');
		   $otitle2 = $playerTitle.find('h3');
		   $orent = $playerRent.find('p');
		   $oextras = $playerExtras.find('p');
		   $oinfo = $playerText1.find('p');
		   
		   
		   //code to close overlay
		$close.click(function(){
			$overlayContent.fadeOut(400, function(){				
				$overlay.slideUp(600, function(){					
					if( meplayer ) {						
						meplayer.pause();
						meplayer = '';
					}
					
					$overlayContent.children().not('div.details').remove();
					$mask.fadeOut(400);
				});
			});
		});
		   
		  }


function slideSwitch(activeslide) {
//alert("slideswitching");
    var $active = $('#slideshow'+activeslide+' IMG.active');

    if ( $active.length == 0 ) $active = $('#slideshow'+activeslide+' IMG:last');

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow'+activeslide+' IMG:first');

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 500, function() {
            $active.removeClass('active last-active');
        });
}

$.fn.easyTooltip = function(options){
	  
		// default configuration properties
		var defaults = {	
			xOffset: 10,		
			yOffset: 25,
			tooltipId: "easyTooltip",
			clickRemove: false,
			content: "",
			useElement: ""
		}; 
			
		var options = $.extend(defaults, options);  
		var content;
				
		this.each(function() {  				
			var title = $(this).attr("title");				
			$(this).hover(function(e){											 							   
				content = (options.content != "") ? options.content : title;
				content = (options.useElement != "") ? $("#" + options.useElement).html() : content;
				$(this).attr("title","");									  				
				if (content != "" && content != undefined){
//alert(tooltipId);				
					$("body").append("<div id='slidee"+ options.tooltipId +"'>"+ content +"</div>");		
					$("#slidee" + options.tooltipId)
						.css("position","absolute")
						.css("top",(e.pageY - options.yOffset) + "px")
						.css("left",(e.pageX + options.xOffset) + "px")						
						.css("display","none")
						.fadeIn("fast")
				}
				
				myint=self.setInterval( function(){slideSwitch(options.tooltipId)}, 1000);
			},
			function(){	
				$("#slidee" + options.tooltipId).remove();
				$(this).attr("title",title);
				myint=window.clearInterval(myint);
			});	
			$(this).mousemove(function(e){
				$("#slidee" + options.tooltipId)
					.css("top",(e.pageY - options.yOffset) + "px")
					.css("left",(e.pageX + options.xOffset) + "px")					
			});	
			if(options.clickRemove){
				$(this).mousedown(function(e){
					$("#slidee" + options.tooltipId).remove();
					$(this).attr("title",title);
					myint=window.clearInterval(myint);
				});				
			}
		});
	  
	};



function updateCartHeader(){
var itemTotalQty = $('#jcart').find('[name=current_quantity]'),
	itemSubtotals = $('#jcart').find('[name=current_subtotal]');
				
					
	$('#cart_text').html(itemTotalQty[0].value+' items in cart. ($'+itemSubtotals[0].value+')');
}


function htmlentities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

		
		var path = webroot+'jcart',
			container = $('#jcart'),
			token = $('[name=jcartToken]').val(),
			tip = $('#jcart-tooltip');

		var config = (function() {
			var config = null;
			$.ajax({
				url: path + '/config-loader.php',
				data: {
					"ajax": "true"
				},
				dataType: 'json',
				async: false,
				success: function(response) {
					config = response;
				},
				error: function() {
					alert('Ajax error: Edit the path in jcart.js to fix.');
				}
			});
			return config;
		}());

		var setup = (function() {
			if(config.tooltip === true) {
				tip.text(config.text.itemAdded);
	
				// Tooltip is added to the DOM on mouseenter, but displayed only after a successful Ajax request
				$('.jcart [type=submit]').mouseenter(
					function(e) {
						var x = e.pageY + 25,
							y = e.pageX + -10;
						$('body').append(tip);
						tip.css({top: y + 'px', left: x + 'px'});
					}
				)
				.mousemove(
					function(e) {
						var y = e.pageY + 25,
						x = e.pageX + -10;
						tip.css({top: y + 'px', left: x + 'px'});
					}
				)
				.mouseleave(
					function() {
						tip.hide();
					}
				);
			}

			// Remove the update and empty buttons since they're only used when javascript is disabled
			$('#jcart-buttons').remove();

			// Default settings for Ajax requests
			$.ajaxSetup({
				type: 'POST',
				url: path + '/relay.php',
				success: function(response) {
					// Refresh the cart display after a successful Ajax request
					container.html(response);
					$('#jcart-buttons').remove();
				},
				// See: http://www.maheshchari.com/jquery-ajax-error-handling/
				error: function(x, e) {
					var s = x.status, 
						m = 'Ajax error: ' ; 
					if (s === 0) {
						m += 'Check your network connection.';
					}
					if (s === 404 || s === 500) {
						m += s;
					}
					if (e === 'parsererror' || e === 'timeout') {
						m += e;
					}
					alert(m);
				}
			});
		}());

		// Check hidden input value
		// Sent via Ajax request to jcart.php which decides whether to display the cart checkout button or the PayPal checkout button based on its value
		// We normally check against request uri but Ajax update sets value to relay.php

		// If this is not the checkout the hidden input doesn't exist and no value is set
		var isCheckout = $('#jcart-is-checkout').val();

		function add(form) {
			// Input values for use in Ajax post
			var itemQty = form.find('[name=' + config.item.qty + ']'),
				itemAdd = form.find('[name=' + config.item.add + ']');
			// Add the item and refresh cart display
			$.ajax({
				data: form.serialize() + '&' + config.item.add + '=' + itemAdd.val(),
				success: function(response) {

					// Momentarily display tooltip over the add-to-cart button
					if (itemQty.val() > 0 && tip.css('display') === 'none') {
						//tip.fadeIn('100').delay('400').fadeOut('100');
					}
                
					container.html(response);
					$('#jcart-buttons').remove();
					
				updateCartHeader();
					
				}
			});
		}

		function update(input) {
			// The id of the item to update
			var updateId = input.parent().find('[name="jcartItemId[]"]').val();

			// The new quantity
			var newQty = input.val();

			// As long as the visitor has entered a quantity
			if (newQty) {

				// Update the cart one second after keyup
				var updateTimer = window.setTimeout(function() {

					// Update the item and refresh cart display
					$.ajax({
						data: {
							"jcartUpdate": 1, // Only the name in this pair is used in jcart.php, but IE chokes on empty values
							"itemId": updateId,
							"itemQty": newQty,
							"jcartIsCheckout": isCheckout,
							"jcartToken": token
						}
					});
				}, 1000);
			}

			// If the visitor presses another key before the timer has expired, clear the timer and start over
			// If the timer expires before the visitor presses another key, update the item
			input.keydown(function(e){
				if (e.which !== 9) {
					window.clearTimeout(updateTimer);
				}	
			});
		}

		function remove(link) {
			// Get the query string of the link that was clicked
			var queryString = link.attr('href');
			queryString = queryString.split('=');

			// The id of the item to remove
			var removeId = queryString[1];

			// Remove the item and refresh cart display
			$.ajax({
				type: 'GET',
				data: {
					"jcartRemove": removeId,
					"jcartIsCheckout": isCheckout
				},
				complete: function() {
					updateCartHeader();
				}
			});
			
			
		}

		// Add an item to the cart
		

		// Prevent enter key from submitting the cart
		container.keydown(function(e) {
			if(e.which === 13) {
				e.preventDefault();
			}
		});

		// Update an item in the cart
		container.delegate('[name="jcartItemQty[]"]', 'keyup', function(){
			update($(this));
		});

		// Remove an item from the cart
		container.delegate('.jcart-remove', 'click', function(e){
			remove($(this));
			e.preventDefault();
			
		});

	//}()); // End JCART namespace
	
var mainpage='';
//form verification code




$("#sign_in_form").submit(function()
	{
	//alert("sign");
	var usern = $('#username').val(),
	passw = $('#password').val();
	
	
	$("#loginresult").html('Verifying Login Info...');
		//remove all the class add the messagebox classes and start fading
		//$("#loginresult").css('display', 'inline');
		//check the username exists or not from ajax
		$.post(webroot+"/purchaser/phpScripts/loginAjax.php",{ 
		userName:usern,
		passWord:passw},
		function(data)
        {
		//alert(data);
		  if(data=='success') //if correct login detail
		  {
		  $.cookie("VCc", usern+' '+passw, { expires : 10 });
		   document.location=document.location.href;
		 
		  } 
		  else if (data=='reset')
		  {
		  
		  $("#loginresult").html('');
		   $("#rusername").val(usern);
		   $("#temppass").val(passw);
		  $("#contact_part2").slideUp({
					duration: 700,
					easing: 'easeOutExpo',
					complete:function(){
						$("#contact_part4").slideDown({
					duration: 400,
					easing: 'easeOutBack',
					complete:function(){
						$("#contact_part4 .content div").animate({opacity:1},400);
					}
					});
					}
					}
				
				
				);
		  
		  }
		  else 
		  {

			 $("#loginresult").html('<h5>Incorrect Login - <a id="forgotpasssubmit" href="#">Forgot Password?</a></h5>');
			
			 
			 Cufon.replace('#loginresult');
			}
			});	
         
				
       
 		return false; //not to post the  form physically
	});
	
	
$("#resetpass_form").submit(function()
	{
	
	var usern = $('#rusername').val(),
	passw = $('#passwordr').val(),
	passw2 = $('#passwordr2').val(),
	temppass = $('#temppass').val();
	
	if (passw==''){
	$('#rpasswordCheck').html('Please Fill In Both Password Fields');
$('#rpasswordCheck').css('color', 'red');
okaytoreg2=false;
}else if (passw2==''){
$('#rpasswordCheck').html('Please Fill In Both Password Fields');
$('#rpasswordCheck').css('color', 'red');
okaytoreg2=false;
}
	
	if (okaytoreg2==true){
	$("#rsresult").html('Changing Password...');
	
	
		//remove all the class add the messagebox classes and start fading
		//check the username exists or not from ajax
		$.post(webroot+"/purchaser/phpScripts/resetpassAjax.php",{ 
		userName:usern,
		passWord:passw,
		temppass:temppass},
		function(data)
        {
		//alert(data);
		  if(data=='success') //if correct login detail
		  {
		  $.cookie("VCc", usern+' '+passw, { expires : 10 });
		   //document.location=mainpage;
		   
		   $("#rsresult").animate({opacity:0}).show();
		   
		     $("#rsresult").html('<h5>Password Successfully Reset - Logging In..');
			 Cufon.replace('#rsresult');
			 
			  $('#rsresult').animate({
    opacity: 1,
	}, 1200, function() {
   document.location=webroot;
  });
			
			 
		  }
		  else if(data=='failedpassword')
		  {
		  	 $("#rsresult").html('<h5>Password Must Be At Least 6 Characters</h5>');
			 Cufon.replace('#rsresult');
          }else{
		   $("#rsresult").html('<h5>There was an error, Try Again.</h5>');
			 Cufon.replace('#rsresult');
		  }
				
		});
 		
		}
		return false; //not to post the  form physically
	});	
	

	$("#create_account_form").submit(function()
	{
	
	var usern = $('#signup_username').val(),
	passw = $('#signup_password').val(),
	passw2 = $('#signup_password2').val(),
	email = $('#contact_email').val();
	
	if (usern==''){
	$('#usernameCheck').html('Username Must Be At Least 4 Characters');
$('#usernameCheck').css('color', 'red');
	okaytoreg=false;
	}
	
	if (passw==''){
	$('#passwordCheck').html('Password Must Be At Least 6 Characters');
$('#passwordCheck').css('color', 'red');
okaytoreg=false;
	}
	
	if (passw2==''){
	$('#passwordCheck2').html('Password Must Be At Least 6 Characters');
$('#passwordCheck2').css('color', 'red');
okaytoreg=false;
	}
	
	
	if (email==''){
	$('#emailCheck').html('Please Enter a Valid Email Address');
$('#emailCheck').css('color', 'red');
okaytoreg=false;
	}
	
	if (okaytoreg==true){
	
	
		//remove all the class add the messagebox classes and start fading
		//$("#suresult").html('<h5>Creating Account</h5>');
		//Cufon.replace('#suresult');
		//check the username exists or not from ajax
		$.post(webroot+"/purchaser/phpScripts/registerAjax.php",{ 
		userName:usern,
		passWord:passw,
		Email:email},
		function(data)
        {
		//alert(data);
		  if(data=='success'||data=='failedmailer') //if correct login detail
		  {
		  $('#emailCheck', '#passwordCheck2', '#usernameCheck', '#passwordCheck').html('Registration Complete');
$('#emailCheck', '#passwordCheck2', '#usernameCheck', '#passwordCheck').css('color', 'green');

		  
		  $.cookie("VCc", usern+' '+passw, { expires : 10 });
		   document.location=webroot+'?req=newest';
		 
		  }
		  else if (data=='failedblank')
		  {
		  	$('#emailCheck', '#passwordCheck2', '#usernameCheck', '#passwordCheck').html('Please Fill In All Fields');
$('#emailCheck', '#passwordCheck2', '#usernameCheck', '#passwordCheck').css('color', 'red');
okaytoreg=false;
          }
		  else if (data=='userexists'||data=='emailexists')
		  {
		  	$('#usernameCheck', '#emailCheck').html('User Exists');
$('#usernameCheck', '#emailCheck').css('color', 'red');
	okaytoreg=false;
				}
				else if (data=='failedemail')
		  {
		  	$('#emailCheck').html('Please Enter a Valid Email Address');
$('#emailCheck').css('color', 'red');
okaytoreg=false;
				}else if (data=='failedusername')
		  {
		  	$("#suresult").html('<h5>Username Must Be At Least 4 Characters</h5>');
		Cufon.replace('#suresult');
				}else if (data=='failedpassword')
		  {
		  	$('#passwordCheck2, #passwordCheck').html('Password Must Be At Least 6 Characters');
$('#passwordCheck2, #passwordCheck').css('color', 'red');
okaytoreg=false;
				}
        });
		}
 		return false; //not to post the  form physically
	});
	
$("#forgotpass_form").submit(function()
	{
	//alert("sign");
	var usern = $('#fusername').val(),
	email = $('#femail').val();
	
	
	$("#fpresult").html('Preparing Email...');
		//remove all the class add the messagebox classes and start fading
		//$("#loginresult").css('display', 'inline');
		//check the username exists or not from ajax
		$.post(webroot+"/purchaser/phpScripts/forgotpassAjax.php",{ 
		userName:usern,
		passWord:email},
		function(data)
        {
		//alert(data);
		  if(data=='success') //if correct login detail
		  {
		   $("#fpresult").html('<h5>Password sent to '+email+' - <a id="forgotpasssent" href="#">Continue</a></h5>');
		Cufon.replace('#fpresult');
		
		  }else  if(data=='error'){
		  $("#fpresult").html('<h5>There Was a System Error - Please Try Again.</h5>');
			
			 
			 Cufon.replace('#fpresult');
			 
			}else{
			$("#fpresult").html('<h5>Invalid Account Info.</h5>');
			
			 
			 Cufon.replace('#fpresult');
			}
			});	
         
				
       
 		return false; //not to post the  form physically
	});


function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};


$('input#passwordr2').bind("blur",function(){
var b=$('input#passwordr2').val();
var a=$('input#passwordr').val();
if(b!=a){
$('#rpasswordCheck2').html('Passwords Do Not Match');
$('#rpasswordCheck2').css('color', 'red');
okaytoreg2=false;
	}else{
	$('#rpasswordCheck2').html('Passwords Match');
$('#rpasswordCheck2').css('color', 'green');
okaytoreg2=true;
	}
});


$('input#passwordr').bind("blur",function(){
var b=$('input#passwordr').val();

if (b.length<6){
$('#rpasswordCheck').html('Password Must Be At Least 6 Characters');
$('#rpasswordCheck').css('color', 'red');
okaytoreg2=false;
}else{
$('#rpasswordCheck').html('Password OK!');
$('#rpasswordCheck').css('color', 'green');
okaytoreg2=true;
}
});


$('input#signup_password2').bind("blur",function(){
var b=$('input#signup_password').val();
var a=$('input#signup_password2').val();
if(b!=a){
$('#passwordCheck2').html('Passwords Do Not Match');
$('#passwordCheck2').css('color', 'red');
okaytoreg=false;
	}else{
	$('#passwordCheck2').html('Passwords Match');
$('#passwordCheck2').css('color', 'green');
okaytoreg=true;
	}
});


$('input#signup_password').bind("blur",function(){
var b=$('input#signup_password').val();

if (b.length<6){
$('#passwordCheck').html('Password Must Be At Least 6 Characters');
$('#passwordCheck').css('color', 'red');
okaytoreg=false;
}else{
$('#passwordCheck').html('Password OK!');
$('#passwordCheck').css('color', 'green');
okaytoreg=true;
}
});

$('input#signup_username').bind("blur",function(){
var u=$('input#signup_username').val();
var check=false;
if (u.length<4){
$('#usernameCheck').html('Username Must Be At Least 4 Characters');
$('#usernameCheck').css('color', 'red');
okaytoreg=false;
}else if(u.length>45){
$('#usernameCheck').html('Username Must Be Less Than 45 Characters');
$('#usernameCheck').css('color', 'red');
okaytoreg=false;
}else if(u.indexOf('&')!=-1||u.indexOf('.')!=-1||u.indexOf('+')!=-1||u.indexOf('?')!=-1||u.indexOf(' ')!=-1||u.indexOf(';')!=-1){
$('#usernameCheck').html('Username Has An Invalid Character Or Space');
$('#usernameCheck').css('color', 'red');
okaytoreg=false;
}else{
$('#usernameCheck').html('Checking Availability....');
$('#usernameCheck').css('color', 'green');
okaytoreg=true;
check=true;
}

if (check==true){
$.ajax({
		type: 'POST',
		url: webroot+'/purchaser/phpScripts/verifyAjax.php',
		data: 'requestType=UserName&value='+u,
		dataType: 'xml',
		success: function(data){
	$response = $(data).find('response').text();
		
		if ($response=='nogood'){
			$('#usernameCheck').html('This Username Is Not Available');
$('#usernameCheck').css('color', 'red');	
okaytoreg=false;
		}else{
		$('#usernameCheck').html('Username OK!');
$('#usernameCheck').css('color', 'green');
okaytoreg=true;
		
	}
	}
	});	
}

});

$('input#contact_email').bind("blur",function(){
var u=$('input#contact_email').val();
var check=false;

if( !isValidEmailAddress( u ) ) 
{ 
$('#emailCheck').html('Invalid Email Address');
$('#emailCheck').css('color', 'red');
okaytoreg=false;
}else{
$('#emailCheck').html('Checking Availability....');
$('#emailCheck').css('color', 'green');
okaytoreg=true;
check=true;
}

if (check==true){
$.ajax({
		type: 'POST',
		url: webroot+'purchaser/phpScripts/verifyAjax.php',
		data: 'requestType=Email&value='+u,
		dataType: 'xml',
		success: function(data){
	$response = $(data).find('response').text();
		
		if ($response=='nogood'){
			$('#emailCheck').html('This Email Is Aready In Use <a href="#" style="color:#f9c85f;" id="forgotpass_su">Forgot Password?</a>');
$('#emailCheck').css('color', 'red');
okaytoreg=false;	
		}else{
		$('#emailCheck').html('Email OK!');
$('#emailCheck').css('color', 'green');
		okaytoreg=true;
	}
	}
	});	
}

});

	
// form verification end
	
	var requestType='',
	    startRange='0',
	    endRange='20',
	    sortBy='',
	    filterRate='',
	    filterCat='',
	    filterGenre='',
	    userId='',
	    seriesId='',
	    seasonId='',
		searchTerms='',
		currentPage=1,
		changed=false;
	
	var $ccgallery = $('#ccgallery'),
		$thumbGallery = $('#thumbGallery'),
		$thumbList = $('#thumbGallery').find('ul'),						
		msie = $.browser.msie ? true : false,
		ie9js = msie && $.browser.version < 9 && IE7.recalc ? true : false,
		xmlFile = webroot+'/purchaser/phpScripts/getAjax.php';
	
	// First check if mobile devices are to be detected and if yes serve them an alternate xml file
	if( $ccgallery.data('mobile') === true ) {
		$.ajax({
			type: 'GET',
			url: 'includes/mobile.php',
			dataType: 'text',
			success: function(data) {
				if( data = 'true') {
					xmlFile = 'config-mobile.xml';
				}
			}
		});		
	}else{
	//currentPage=1;
	$.ajax({
		type: 'POST',
		url: webroot+'purchaser/phpScripts/getAjax.php',
		data: 'requesttype=start&startRange=0&endRange=20',
		dataType: 'xml',
		success: function(data){
	//alert(data.getElementsByTagName("CCGallery").firstChild.nodeValue);
	
	var getethisthing;
	
	$(data).find('CCGallery').each(function(){
getethisthing = $(this).find('u').text();
});	
	
		if (getethisthing!='no'){
			ccgalleryCreate( $(data) );
		}else{
		document.getElementById('MainTitleHead').innerHTML = 'NO RESULTS FOUND';
	Cufon.replace('#MainTitleHead');
	
	$('#ccgallery').toggle();

	
		}
		
		}
	});	
	
	
	}

	

    $.fn.center = function () {
	
	var catwd = $('#catTitle').outerWidth(),
	 genwd = $('#genTitle').outerWidth(),
	 ratwd = $('#genRating').outerWidth(),
	 sortwd = $('#sortBy').outerWidth();

	finalWidth = catwd+genwd+ratwd+sortwd;
    //this.css("position","relative");
    //this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
	this.css("margin-left", "0px");
	
	if ($.browser.webkit){
	this.css("left", ((($(window).width() - finalWidth) / 2) + $(window).scrollLeft()) - 220+ "px");
	}else{
    this.css("left", ((($(window).width() - finalWidth) / 2) + $(window).scrollLeft()) - 505+ "px");
	}
	//this.css("margin-left", ($(window).width()/2)-(finalWidth / 2) + "px");
	//alert(finalWidth);
    return this;
    }

	function reloadGallery($requestType, $startRange, $endRange, $sortBy, $filterRate, $filterCat, $filterGenre, $userId, $seriesId, $seasonId, $searchTerms){
	//added=false;
$thumbList.undelegate('img', 'click');


	$.ajax({
		type: 'POST',
		url: webroot+'purchaser/phpScripts/getAjax.php',
		data: 'requestType='+$requestType+'&startRange='+$startRange+'&endRange='+$endRange+'&sortBy='+$sortBy+'&filterRate='+$filterRate+'&filterCat='+$filterCat+'&filterGenre='+$filterGenre+'&userId='+$userId+'&seriesId='+$seriesId+'&seasonId='+$seasonId+'&searchTerms='+$searchTerms,
		dataType: 'xml',
		success: function(data){
	if ($requestType=='search'){
	document.getElementById('MainTitleHead').innerHTML = 'Search Results';
	Cufon.replace('#MainTitleHead');
	}else if ($requestType=='series'){
	document.getElementById('MainTitleHead').innerHTML = 'Series';
	Cufon.replace('#MainTitleHead');
	}else if ($requestType=='season'){
	document.getElementById('MainTitleHead').innerHTML = 'Series Season'+$seasonId;
	Cufon.replace('#MainTitleHead');
	}else if ($requestType=='purchased'||$requestType=='myvideos'){
	document.getElementById('MainTitleHead').innerHTML = 'Your Purchases';
	Cufon.replace('#MainTitleHead');
	}else if ($requestType=='uploads'){
	document.getElementById('MainTitleHead').innerHTML = 'Your Uploads';
	Cufon.replace('#MainTitleHead');
	}else{
	document.getElementById('MainTitleHead').innerHTML = 'Newest Videos';
	Cufon.replace('#MainTitleHead');
	}
			ccgalleryCreate( $(data) );
				
		}
	});	
	}
	
function secondsToTime(secs){
    var hours = Math.floor(secs / (60 * 60));
   
    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);
 
    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);
   
	var formattedtime = hours+":"+minutes+":"+seconds;
	
    return formattedtime;
}

var TotalSeconds;
	
function Tick() {
    TotalSeconds -= 1;
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}

function UpdateTimer() {
   // $orent = document.getElementById('#playerRent');
    $('#playerRent').html('<h3>Rental Time Left: '+secondsToTime(TotalSeconds)+'</h3>');
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}	
	
	function activateRental($vidid){
	//added=false;
//$thumbList.undelegate('img', 'click');


	$.ajax({
		type: 'POST',
		url: webroot+'purchaser/phpScripts/activateAjax.php',
		data: 'vidID='+$vidid,
		success: function(data){
		if (data=='success'){
			//$orent = document.getElementById('#playerRent');
		//$('#playerRent').html('<h3>Rental Time Left: '+secondsToTime(86400)+'</h3>');
	       
      // window.setTimeout("Tick()", 1000);
	  document.location=webroot+'?req=vid&id='+$vidid;
	  
		}else{
	
		
	}
		

				
		}
	});	
	}
	

	
	
	/***************** function to create the gallery html structure **********************/
	function ccgalleryCreate( $galleryConfig ) {	
	
	//$('#filter-menu menu').center();
	
	var $files = $galleryConfig.find('file'),
	    $fullCount = $files.find('count');
		
		//alert($fullCount);
		
	if ($fullCount.eq(0).text()!='none'){
	}
	
	
	
	
		
		var	$coverPics = $files.find('cover'),
			$thumbs = $files.find('thumb'),
			$titles = $files.find('title'),
			$descriptions = $files.find('description'),
			$ratingimg = $files.find('ratingimg'),
			$hd = $files.find('hd'),
			$rating = $files.find('rating'),
			$seriesname = $files.find('seriesname'),
			$pageNumber = $files.find('pagenum'),
			itemnum = $files.length,			
			loadCounter = 0;
		
	
		
		 var pageCount = (parseInt($fullCount.eq(0).text())-1)/20;
var pageNum = parseInt($pageNumber.eq(0).text());

	var pagination = '';
		//var setcurrent='';
		//alert(pageCount);
		//alert (pageCount);
		
		if (pageCount>1){
		
		//alert(pageNum);
		for (var i = 0; i <= pageCount; i++){
		if (pageNum==(i+1)){
		//setcurrent=i;
		pagination+='<a class="navbuttons active" id="'+(i+1)+'" data-type="'+(i+1)+'">Page '+(i+1)+'</a>';
		}else{
		pagination+='<a class="navbuttons" id="'+(i+1)+'" data-type="'+(i+1)+'">Page '+(i+1)+'</a>';
		}
}


}

$('#pageButtons').html( pagination );

		
		
		// Fill up the Thumbnail gallery
		var thumbli = '';
		
		for( var i = 0; i < itemnum; i++ ) {
		
		var idArrayz = $thumbs.eq(i).text().split('/');
		
			thumbli += '<li data-id="'+ (i+1) +'" data-type="'+ $files.eq(i).attr('type') +'" data-genre="'+ $files.eq(i).attr('genre') +'">';
			if ($titles.eq(i).text().length>30&&$titles.eq(i).text().length<40){
			thumbli += '<h4>'+$titles.eq(i).text()+'</h4>';

			}else if ($titles.eq(i).text().length>=40){
			thumbli += '<h5><a href="'+webroot+siteroot+'?req=vid&id='+idArrayz[3]+'" title="'+$titles.eq(i).text()+'" style="color:#fff;">'+$titles.eq(i).text()+'</a></h5>';
			}else{
			thumbli += '<h3><a href="'+webroot+siteroot+'?req=vid&id='+idArrayz[3]+'" title="'+$titles.eq(i).text()+'" style="color:#fff;">'+$titles.eq(i).text()+'</a></h3>';
			}
			
			http://c1385182.cdn.cloudfiles.rackspacecloud.com/3z6kOYlKnE29jVBzQlH0iOh5RW5IwZfO.1.jpg
			thumbli += '<img class="mainthumbimg" id="thumb'+ (i+1) +'" src="'+ $thumbs.eq(i).text() +'.1.jpg" alt="" />';
			
			
			
			thumbli += '<div class="details">';
			if ($seriesname.eq(i).text().length>25&&$seriesname.eq(i).text().length<30){
			thumbli += '<h3>'+$seriesname.eq(i).text()+'</h3>';

			}else if ($seriesname.eq(i).text().length>=30&&$seriesname.eq(i).text().length<40){
			thumbli += '<h4>'+$seriesname.eq(i).text()+'</h4>';
			}else if ($seriesname.eq(i).text().length>=40){
			thumbli += '<h5>'+$seriesname.eq(i).text()+'</h5>';
			}else{
			thumbli += '<h2>'+$seriesname.eq(i).text()+'</h2>';
			}

			
			//thumbli += '<p class="description">'+ $descriptions.eq(i).text() +'</p>';
			thumbli += '<img src="'+ webroot + $rating.eq(i).text() +'" alt="" />';
			thumbli += '<img src="'+ webroot + $hd.eq(i).text() +'" alt="" />';
			thumbli += '<img src="'+ webroot + $ratingimg.eq(i).text() +'" alt="" />';
			thumbli += '</div>';
			thumbli += '</li>';
			//$("#thumb"+ (i+1)).tooltip({ effect: 'slide'});
		}
		
		$thumbList.html( thumbli );
		


			startmode = 'thumbnails';
			
		
		
		$ccgallery.find('img').load(function(){			
			loadCounter++;
			if( loadCounter === 2*itemnum ) {
				$ccgallery.css({ height: 'auto', background: 'none' });
				
			
					$thumbGallery.fadeIn(600);
					
				
				
				ccgallerySetup( itemnum, $files );
			}			
		});		
		
	
		
		
	}  //end ccgalleryCreate()
		
		
		
	/******************** function to setup all the workings of the gallery **************************/
	function ccgallerySetup( itemnum, $files ) {
		
		// action to take when clicking on toolbar buttons
		var $thumbListClone = $thumbList.clone();
			

			 $('#SearchInput').keypress(function(e) {
        if(e.which == 13) {
		searchTerms=document.getElementById('SearchInput').value;
		
            if (searchTerms!=''&&searchTerms!='Enter Search Terms'){
doSearch(searchTerms);      
}
        }
    });


		$('#searchBtn').click(function() {
			
	searchTerms=document.getElementById('SearchInput').value;
	
if (searchTerms!=''&&searchTerms!='Enter Search Terms'){
doSearch(searchTerms);      
}

});

function doSearch($searchTerms){
startRange='0';
	 endRange='20';
	requestType='search';
	searchTerms=$searchTerms;
	reloadGallery(requestType, startRange, endRange, sortBy, filterRate, filterCat, filterGenre, userId, seriesId, seasonId, searchTerms);
}
			
			$('#searchBtn').click(function() {
			requestType='search';
			searchTerms=document.getElementById('SearchInput').value;
if (searchTerms!=''&&searchTerms!='Enter Search Terms'){

             startRange='0';
	         endRange='20';
	
	reloadGallery(requestType, startRange, endRange, sortBy, filterRate, filterCat, filterGenre, userId, seriesId, seasonId, searchTerms);
}

});
			$('#cat').undelegate();
			$('#cat').delegate('a.navbuttonsgen', 'click', function(){
			var $this = $(this);
			//$('#filter-menu ul').fadeOut(105).show();
		//document.getElementById('catHover').fadeOut(105).show();
			//$(this).parent('li').find(".subline").removeClass("current");
				//thisindex = $this.index('a.navbuttons'),
				//sections = $('section.displayStyle');
				
				$catTitle = $this.data('type').replace(/_/g, " ");
				//$this.data('type');
				if ($catTitle=="Feature Film"||$catTitle=="Short Film"){
				changed=true;
				//$('#ratingList').undelegate();
				document.getElementById('ratingList').innerHTML = '<a href="#" title=""><span id="genRating" class="cufon">Rating: All</span><span class="subline"></span></a><ul><li><a class="navbuttonsrate" id="all" data-type="all">All Ratings</a></li><li><a class="navbuttonsrate" id="G" data-type="G">G</a></li><li><a class="navbuttonsrate" id="PG" data-type="PG">PG</a></li><li><a class="navbuttonsrate" id="PG-13" data-type="PG-13">PG-13</a></li><li><a class="navbuttonsrate" id="R" data-type="R">R</a></li><li><a class="navbuttonsrate" id="NC-17" data-type="NC-17">NC-17</a></li><li><a class="navbuttonsrate" id="NR" data-type="NR">UnRated</a></li></ul>';
				//$('categoryList').undelegate();
				document.getElementById('categoryList').innerHTML = '<a href="#" title=""><span id="genTitle" class="cufon">Genre: All</span><span class="subline"></span></a><ul class="gen1"><li><a class="navbuttonscat" id="all" data-type="all">All Genres</a></li><li><a class="navbuttonscat" id="Action_and_Adventure" data-type="Action_and_Adventure">Action & Adventure</a></li><li><a class="navbuttonscat" id="Animals" data-type="Animals">Animals</a></li><li><a class="navbuttonscat" id="Animated" data-type="Animated">Animated</a></li><li><a class="navbuttonscat" id="Arts" data-type="Arts">Arts</a></li><li><a class="navbuttonscat" id="Biography" data-type="Biography">Biography</a></li><li><a class="navbuttonscat" id="Comedy" data-type="Comedy">Comedy</a></li><li><a class="navbuttonscat" id="Concerts" data-type="Concerts">Concerts</a></li></ul><ul class="gen2"><li><a class="navbuttonscat" id="Crime" data-type="Crime">Crime</a></li><li><a class="navbuttonscat" id="Cult_Classics" data-type="Cult_Classics">Cult Classics</a></li><li><a class="navbuttonscat" id="Documentary" data-type="Documentary">Documentary</a></li><li><a class="navbuttonscat" id="Drama" data-type="Drama">Drama</a></li><li><a class="navbuttonscat" id="Epic" data-type="Epic">Epic</a></li><li><a class="navbuttonscat" id="Family" data-type="Family">Family</a></li><li><a class="navbuttonscat" id="Fantasy" data-type="Fantasy">Fantasy</a></li><li><a class="navbuttonscat" id="Foreign" data-type="Foreign">Foreign</a></li></ul><ul class="gen3"><li><a class="navbuttonscat" id="Historical" data-type="Historical">Historical</a></li><li><a class="navbuttonscat" id="Horror" data-type="Horror">Horror</a></li><li><a class="navbuttonscat" id="Martial_Arts" data-type="Martial_Arts">Martial Arts</a></li><li><a class="navbuttonscat" id="Musical" data-type="Musical">Musical</a></li><li><a class="navbuttonscat" id="Mystery" data-type="Mystery">Mystery</a></li><li><a class="navbuttonscat" id="Nature" data-type="Nature">Nature</a></li><li><a class="navbuttonscat" id="Religious" data-type="Religious">Religious</a></li><li><a class="navbuttonscat" id="Romance" data-type="Romance">Romance</a></li></ul><ul class="gen4"><li><a class="navbuttonscat" id="Science_Fiction" data-type="Science_Fiction">Science Fiction</a></li><li><a class="navbuttonscat" id="Silent" data-type="Silent">Silent</a></li><li><a class="navbuttonscat" id="Sports" data-type="Sports">Sports</a></li><li><a class="navbuttonscat" id="War" data-type="War">War</a></li><li><a class="navbuttonscat" id="Western" data-type="Western">Western</a></li></ul>';
				}else if ($catTitle=="TV Series"||$catTitle=="Web Series"||$catTitle=="How To"){
				changed=true;
				//$('#ratingList').undelegate();
				document.getElementById('ratingList').innerHTML = '<a href="#" title=""><span id="genRating" class="cufon">Rating: All</span><span class="subline"></span></a><ul><li><a class="navbuttonsrate" id="all" data-type="all">All Ratings</a></li><li><a class="navbuttonsrate" id="TV-Y" data-type="TV-Y">TV-Y</a></li><li><a class="navbuttonsrate" id="TV-Y7" data-type="TV-Y7">TV-Y7</a></li><li><a class="navbuttonsrate" id="TV-Y7-FV" data-type="TV-Y7-FV">TV-Y7-LV</a></li><li><a class="navbuttonsrate" id="TV-G" data-type="TV-G">TV-G</a></li><li><a class="navbuttonsrate" id="TV-PG" data-type="TV-PG">TV-PG</a></li><li><a class="navbuttonsrate" id="TV-14" data-type="TV-14">TV-14</a></li><li><a class="navbuttonsrate" id="TV-MA" data-type="TV-MA">TV-MA</a></li><li><a class="navbuttonsrate" id="NR" data-type="NR">UnRated</a></li></ul>';
				//$('#categoryList').undelegate();
				document.getElementById('categoryList').innerHTML = '<a href="#" title=""><span id="genTitle" class="cufon">Genre: All</span><span class="subline"></span></a><ul class="gen1"><li><a class="navbuttonscat" id="all" data-type="all">All Genres</a><li><a class="navbuttonscat" id="Animals_and_Pets" data-type="Animals_and_Pets">Animals & Pets</a></li><li><a class="navbuttonscat" id="Animation_and_Cartoons" data-type="Animation_and_Cartoons">Animation & Cartoons</a></li><li><a class="navbuttonscat" id="Art_and_Design" data-type="Art_and_Design">Art & Design</a></li><li><a class="navbuttonscat" id="Autos_and_Transportation" data-type="Autos & Transportation">Autos & Transportation</a></li><li><a class="navbuttonscat" id="Business_and_Industry" data-type="Business_and_Industry">Business & Industry</a></li><li><a class="navbuttonscat" id="Careers_and_Financial" data-type="Careers_and_Financial">Careers & Financial</a></li><li><a class="navbuttonscat" id="Clothing_and_Fashion" data-type="Clothing_and_Fashion">Clothing & Fashion</a></li><li><a class="navbuttonscat" id="Computers_and_Hardware" data-type="Computers_and_Hardware">Computers & Hardware</a></li><li><a class="navbuttonscat" id="Comedy_and_Standup" data-type="Comedy_and_Standup">Comedy & Standup</a></li><li><a class="navbuttonscat" id="Dance_and_Performance" data-type="Dance_and_Performance">Dance & Performance</a></li></ul><ul class="gen2"><li><a class="navbuttonscat" id="Dating_and_Mating" data-type="Dating_and_Mating">Dating & Mating</a></li><li><a class="navbuttonscat" id="Drama_and_Theatre" data-type="Drama_and_Theatre">Drama & Theatre</a></li><li><a class="navbuttonscat" id="Education_and_Learning" data-type="Education_and_Learning">Education & Learning</a></li><li><a class="navbuttonscat" id="Electronics_and_Engineering" data-type="Electronics_and_Engineering">Electronics & Engineering</a></li><li><a class="navbuttonscat" id="Family_and_Community" data-type="Family_and_Community">Family & Community</a></li><li><a class="navbuttonscat" id="Fighting_and_Martial_Arts" data-type="Fighting_and_Martial_Arts">Fighting & Martial Arts</a></li><li><a class="navbuttonscat" id="Film_and_Photography" data-type="Film_and_Photography">Film & Photography</a></li><li><a class="navbuttonscat" id="Food_and_Cooking" data-type="Food_and_Cooking">Food & Cooking</a></li><li><a class="navbuttonscat" id="Gaming_and_Hobbies" data-type="Gaming_and_Hobbies">Gaming & Hobbies</a></li><li><a class="navbuttonscat" id="Gree_and_Environmental" data-type="Green_and_Environmental">Green & Environmental</a></li><li><a class="navbuttonscat" id="Health_and_Fitness" data-type="Health_and_Fitness">Health & Fitness</a></li></ul><ul class="gen3"><li><a class="navbuttonscat" id="Home_and_Garden" data-type="Home_and_Garden">Home & Garden</a></li><li><a class="navbuttonscat" id="Hunting_and_Fishing" data-type="Hunting_and_Fishing">Hunting & Fishing</a></li><li><a class="navbuttonscat" id="Intellectual_and_Psychological" data-type="Intellectual_and_Psychological">Intellectual & Psychological</a></li><li><a class="navbuttonscat" id="Internet_and_Communication" data-type="Internet_and_Communication">Internet & Communication</a></li><li><a class="navbuttonscat" id="Medical_and_Wellness" data-type="Medical_and_Wellness">Medical & Wellness</a></li><li><a class="navbuttonscat" id="Music_and_Musicians" data-type="Music_and_Musicians">Music & Musicians</a></li><li><a class="navbuttonscat" id="News_and_Information" data-type="News_and_Information">News & Information</a></li><li><a class="navbuttonscat" id="Outdoors_and_Adventure" data-type="Outdoors_and_Adventure">Outdoors & Adventure</a></li><li><a class="navbuttonscat" id="Programming_and_Software" data-type="Programming_and_Software">Programming & Software</a></li><li><a class="navbuttonscat" id="Rodeo_and_Livestock" data-type="Rodeo_and_Livestock">Rodeo & Livestock</a></li></ul><ul class="gen4"><li><a class="navbuttonscat" id="Science_and_Technology" data-type="Science_and_Technology">Science & Technology</a></li><li><a class="navbuttonscat" id="Social_and_Partying" data-type="Social_and_Partying">Social & Partying</a></li><li><a class="navbuttonscat" id="Spiritual_and_Religious" data-type="Spiritual_and_Religious">Spiritual & Religious</a></li><li><a class="navbuttonscat" id="Sports_and_Recreation" data-type="Sports_and_Recreation">Sports & Recreation</a></li><li><a class="navbuttonscat" id="Strange_and_Weird" data-type="Strange_and_Weird">Strange & Weird</a></li><li><a class="navbuttonscat" id="Talk_and_Interview" data-type="Talk_and_Interview">Talk & Interview</a></li><li><a class="navbuttonscat" id="Vacation_and_Travel" data-type="Vacation_and_Travel">Vacation & Travel</a></li><li><a class="navbuttonscat" id="Video_and_Audio" data-type="Video_and_Audio">Video & Audio</a></li><li><a class="navbuttonscat" id="Wildlife_and_Nature" data-type="Wildlife_and_Nature">Wildlife & Nature</a></li></ul>';
				}else if ($catTitle=="Event"){
				changed=true;
				//$('#ratingList').undelegate();
				document.getElementById('ratingList').innerHTML = '<a href="#" title=""><span id="genRating" class="cufon">Rating: All</span><span class="subline"></span></a><ul><li><a class="navbuttonsrate" id="all" data-type="all">All Ratings</a></li><li><a class="navbuttonsrate" id="TV-Y" data-type="TV-Y">TV-Y</a></li><li><a class="navbuttonsrate" id="TV-Y7" data-type="TV-Y7">TV-Y7</a></li><li><a class="navbuttonsrate" id="TV-Y7-FV" data-type="TV-Y7-FV">TV-Y7-FV</a></li><li><a class="navbuttonsrate" id="TV-G" data-type="TV-G">TV-G</a></li><li><a class="navbuttonsrate" id="TV-PG" data-type="TV-PG">TV-PG</a></li><li><a class="navbuttonsrate" id="TV-14" data-type="TV-14">TV-14</a></li><li><a class="navbuttonsrate" id="TV-MA" data-type="TV-MA">TV-MA</a></li><li><a class="navbuttonsrate" id="NR" data-type="NR">UnRated</a></li></ul>';
				//$('#categoryList').undelegate();
				document.getElementById('categoryList').innerHTML = '<a href="#" title=""><span id="genTitle" class="cufon">Genre: All</span><span class="subline"></span></a><ul class="gen1"><li><a class="navbuttonscat" id="all" data-type="all">All Genres</a></li><li><a class="navbuttonscat" id="Comedy" data-type="Comedy">Comedy</a></li><li><a class="navbuttonscat" id="Concert" data-type="Concert">Concert</a></li><li><a class="navbuttonscat" id="Consumer_Show" data-type="Consumer_Show">Consumer Show</a></li><li><a class="navbuttonscat" id="Convention_or_Tradeshow" data-type="Convention_or_Tradeshow">Convention or Tradeshow</a></li><li><a class="navbuttonscat" id="Corporate" data-type="Corporate">Corporate</a></li></ul><ul class="gen2"><li><a class="navbuttonscat" id="Graduation" data-type="Graduation">Graduation</a></li><li><a class="navbuttonscat" id="Motivational" data-type="Motivational">Motivational</a></li><li><a class="navbuttonscat" id="Political" data-type="Political">Political</a></li><li><a class="navbuttonscat" id="Religious" data-type="Religious">Religious</a></li><li><a class="navbuttonscat" id="Sales" data-type="Sales">Sales</a></li><li><a class="navbuttonscat" id="Seminar" data-type="Seminar">Seminar</a></li></ul><ul class="gen3"><li><a class="navbuttonscat" id="Spiritual" data-type="Spiritual">Spiritual</a></li><li><a class="navbuttonscat" id="Sporting" data-type="Sporting">Sporting</a></li><li><a class="navbuttonscat" id="Theatre" data-type="Theatre">Theatre</a></li><li><a class="navbuttonscat" id="Wedding" data-type="Wedding">Wedding</a></li></ul>';
				}else if (changed==true){
				changed=false;
				//$('#ratingList').undelegate();
				document.getElementById('ratingList').innerHTML = '<a href="#" title=""><span id="genRating" class="cufon">Rating: All</span><span class="subline"></span></a><ul><li><a class="navbuttonsrate" id="all" data-type="all">All Ratings</a></li><li><a class="navbuttonsrate" id="G" data-type="G">G</a></li><li><a class="navbuttonsrate" id="PG" data-type="PG">PG</a></li><li><a class="navbuttonsrate" id="PG-13" data-type="PG-13">PG-13</a></li><li><a class="navbuttonsrate" id="R" data-type="R">R</a></li><li><a class="navbuttonsrate" id="NC-17" data-type="NC-17">NC-17</a></li><li><a class="navbuttonsrate" id="TV-Y" data-type="TV-Y">TV-Y</a></li><li><a class="navbuttonsrate" id="TV-Y7" data-type="TV-Y7">TV-Y7</a></li><li><a class="navbuttonsrate" id="TV-Y7-FV" data-type="TV-Y7-FV">TV-Y7-FV</a></li><li><a class="navbuttonsrate" id="TV-G" data-type="TV-G">TV-G</a></li><li><a class="navbuttonsrate" id="TV-PG" data-type="TV-PG">TV-PG</a></li><li><a class="navbuttonsrate" id="TV-14" data-type="TV-14">TV-14</a></li><li><a class="navbuttonsrate" id="TV-MA" data-type="TV-MA">TV-MA</a></li><li><a class="navbuttonsrate" id="NR" data-type="NR">UnRated</a></li></ul>';
				//$('#categoryList').undelegate();
				document.getElementById('categoryList').innerHTML = '<a href="#" title=""><span id="genTitle" class="cufon">Genre: All</span><span class="subline"></span></a><ul class="gen1"><li><a class="navbuttonscat" id="all" data-type="all">All Genres</a></li><li><a class="navbuttonscat" id="Action_and_Adventure" data-type="Action_and_Adventure">Action & Adventure</a></li><li><a class="navbuttonscat" id="Animals_and_Pets" data-type="Animals_and_Pets">Animals & Pets</a></li><li><a class="navbuttonscat" id="Animation_and_Cartoon" data-type="Animation_and_Cartoon">Animation & Cartoon</a></li><li><a class="navbuttonscat" id="Art_and_Design" data-type="Art_and_Design">Art & Design</a></li><li><a class="navbuttonscat" id="Autos_and_Transportation" data-type="Autos_and_Transportation">Autos & Transportation</a></li><li><a class="navbuttonscat" id="Biography" data-type="Biography">Biography</a></li><li><a class="navbuttonscat" id="Business_and_Industry" data-type="Business_and_Industry">Business & Industry</a></li><li><a class="navbuttonscat" id="Careers_and_Financial" data-type="Careers_and_Financial">Careers & Financial</a></li><li><a class="navbuttonscat" id="Clothing_and_Fashion" data-type="Clothing_and_Fashion">Clothing & Fashion</a></li><li><a class="navbuttonscat" id="Computers_and_Hardware" data-type="Computers_and_Hardware">Computers & Hardware</a></li><li><a class="navbuttonscat" id="Comedy_and_Standup" data-type="Comedy_and_Standup">Comedy & Standup</a></li><li><a class="navbuttonscat" id="Concerts" data-type="Concerts">Concerts</a></li><li><a class="navbuttonscat" id="Convention_or_Tradeshow" data-type="Convention_or_Tradeshow">Convention or Tradeshow</a></li><li><a class="navbuttonscat" id="Corporate" data-type="Corporate">Corporate</a></li><li><a class="navbuttonscat" id="Crime" data-type="Crime">Crime</a></li></ul><ul class="gen2"><li><a class="navbuttonscat" id="Cult_Classics" data-type="Cult_Classics">Cult Classics</a></li><li><a class="navbuttonscat" id="Dance_and_Performance" data-type="Dance_and_Performance">Dance & Performance</a></li><li><a class="navbuttonscat" id="Dating_and_Mating" data-type="Dating_and_Mating">Dating & Mating</a></li><li><a class="navbuttonscat" id="Documentary" data-type="Documentary">Documentary</a></li><li><a class="navbuttonscat" id="Drama_and_Theatre" data-type="Drama_and_Theatre">Drama & Theatre</a></li><li><a class="navbuttonscat" id="Education_and_Learning" data-type="Education_and_Learning">Education & Learning</a></li><li><a class="navbuttonscat" id="Electronics_and_Engineering" data-type="Electronics_and_Engineering">Electronics & Engineering</a></li><li><a class="navbuttonscat" id="Epic" data-type="Epic">Epic</a></li><li><a class="navbuttonscat" id="Family_and_Community" data-type="Family_and_Community">Family & Community</a></li><li><a class="navbuttonscat" id="Fighting_and_Martial_Arts" data-type="Fighting_and_Martial_Arts">Fighting & Martial Arts</a></li><li><a class="navbuttonscat" id="Food_and_Cooking" data-type="Food_and_Cooking">Food & Cooking</a></li><li><a class="navbuttonscat" id="Foreign" data-type="Foreign">Foreign</a></li><li><a class="navbuttonscat" id="Gaming_and_Hobbies" data-type="Gaming_and_Hobbies">Gaming & Hobbies</a></li><li><a class="navbuttonscat" id="Graduation" data-type="Graduation">Graduation</a></li><li><a class="navbuttonscat" id="Green_and_Environmental" data-type="Green_and_Environmental">Green & Environmental</a></li><li><a class="navbuttonscat" id="Health_and_Fitness" data-type="Health_and_Fitness">Health & Fitness</a></li></ul><ul class="gen3"><li><a class="navbuttonscat" id="Historical" data-type="Historical">Historical</a></li><li><a class="navbuttonscat" id="Horror" data-type="Horror">Horror</a></li><li><a class="navbuttonscat" id="Home_and_Garden" data-type="Home_and_Garden">Home & Garden</a></li><li><a class="navbuttonscat" id="Hunting_and_Fishing" data-type="Hunting_and_Fishing">Hunting & Fishing</a></li><li><a class="navbuttonscat" id="Intellectual_and_Psychological" data-type="Intellectual_and_Psychological">Intellectual & Psychological</a></li><li><a class="navbuttonscat" id="Internet_and_Communication" data-type="Internet_and_Communication">Internet & Communication</a></li><li><a class="navbuttonscat" id="Medical_and_Wellness" data-type="Medical_and_Wellness">Medical & Wellness</a></li><li><a class="navbuttonscat" id="Motivational" data-type="Motivational">Motivational</a></li><li><a class="navbuttonscat" id="Music_and_Musicians" data-type="Music_and_Musicians">Music & Musicians</a></li><li><a class="navbuttonscat" id="News_and_Information" data-type="News_and_Information">News & Information</a></li><li><a class="navbuttonscat" id="Outdoors_and_Adventure" data-type="Outdoors_and_Adventure">Outdoors & Adventure</a></li><li><a class="navbuttonscat" id="Programming_and_Software" data-type="Programming_and_Software">Programming & Software</a></li><li><a class="navbuttonscat" id="Political" data-type="Political">Political</a></li><li><a class="navbuttonscat" id="Rodeo_and_Livestock" data-type="Rodeo_and_Livestock">Rodeo & Livestock</a></li><li><a class="navbuttonscat" id="Romance" data-type="Romance">Romance</a></li><li><a class="navbuttonscat" id="Science_and_Technology" data-type="Science_and_Technology">Science & Technology</a></li></ul><ul class="gen4"><li><a class="navbuttonscat" id="Science_Fiction" data-type="Science_Fiction">Science Fiction</a></li><li><a class="navbuttonscat" id="Seminar" data-type="Seminar">Seminar</a></li><li><a class="navbuttonscat" id="Silent" data-type="Silent">Silent</a></li><li><a class="navbuttonscat" id="Social_and_Partying" data-type="Social_and_Partying">Social & Partying</a></li><li><a class="navbuttonscat" id="Spiritual_and_Religious" data-type="Spiritual_and_Religious">Spiritual & Religious</a></li><li><a class="navbuttonscat" id="Sports_and_Recreation" data-type="Sports_and_Recreation">Sports & Recreation</a></li><li><a class="navbuttonscat" id="Strange_and_Weird" data-type="Strange_and_Weird">Strange & Weird</a></li><li><a class="navbuttonscat" id="Talk_and_Interview" data-type="Talk_and_Interview">Talk & Interview</a></li><li><a class="navbuttonscat" id="Vacation_and_Travel" data-type="Vacation_and_Travel">Vacation & Travel</a></li><li><a class="navbuttonscat" id="Video_and_Audio" data-type="Video_and_Audio">Video & Audio</a></li><li><a class="navbuttonscat" id="War" data-type="War">War</a></li><li><a class="navbuttonscat" id="Wedding" data-type="Wedding">Wedding</a></li><li><a class="navbuttonscat" id="Western" data-type="Western">Western</a></li><li><a class="navbuttonscat" id="Wildlife_and_Nature" data-type="Wildlife_and_Nature">Wildlife & Nature</a></li></ul>';
				}
				
				
				
				document.getElementById('catTitle').innerHTML = 'Category: '+$catTitle;
					
				Cufon.replace('#filter-menu .cufon');
			
				$('#filter-menu').center();

				startRange='0';
	            endRange='20';
				
				
				
				if ($catTitle=='all'){
				filterCat='';
				}else{
				filterCat=$catTitle;
				}
				
				reloadGallery(requestType, startRange, endRange, sortBy, filterRate, filterCat, filterGenre, userId, seriesId, seasonId, searchTerms);
			});
			$('#categoryList').undelegate();
			$('#categoryList').delegate('a.navbuttonscat', 'click', function(){
			var $this = $(this);
			$(this).parent('li').find(".subline").removeClass("current");
				//thisindex = $this.index('a.navbuttons'),
				//sections = $('section.displayStyle');
				
				$genData = $this.data('type').replace(/_/g, " ");
				//$this.data('type');
				
				
				document.getElementById('genTitle').innerHTML = 'Genre: '+$genData;
				Cufon.replace('#filter-menu .cufon');
				$('#filter-menu').center();
				startRange='0';
	            endRange='20';
				
				if ($genData=='all'){
				filterGenre='';
				}else{
				filterGenre=$genData;
				}
				
				reloadGallery(requestType, startRange, endRange, sortBy, filterRate, filterCat, filterGenre, userId, seriesId, seasonId, searchTerms);
			});
			$('#ratingList').undelegate();
			$('#ratingList').delegate('a.navbuttonsrate', 'click', function(){
			var $this = $(this);
			$(this).parent('li').find(".subline").removeClass("current");
				//thisindex = $this.index('a.navbuttons'),
				//sections = $('section.displayStyle');
				
				$rateTitle = $this.data('type');
				//$this.data('type');
				

				document.getElementById('genRating').innerHTML = 'Rating: '+$rateTitle;
				Cufon.replace('#filter-menu .cufon');
				$('#filter-menu').center();
				

				startRange='0';
	            endRange='20';
				
				if ($rateTitle=='all'){
				filterRate='';
				}else{
				filterRate=$rateTitle;
				}
				
				reloadGallery(requestType, startRange, endRange, sortBy, filterRate, filterCat, filterGenre, userId, seriesId, seasonId, searchTerms);
			});
			$('#sortbyList').undelegate();
			$('#sortbyList').delegate('a.navbuttonssort', 'click', function(){
			var $this = $(this),
				
				
				$sortTitle = $this.data('type').replace(/_/g, " ");
			
				

				document.getElementById('sortBy').innerHTML = 'Sort By: '+$sortTitle;
				Cufon.replace('#filter-menu .cufon');
				$('#filter-menu').center();
				

				startRange='0';
	            endRange='20';
				
				if ($sortTitle=='Newest'){
				sortBy='';
				}else{
				sortBy=$sortTitle;
				}
				
				reloadGallery(requestType, startRange, endRange, sortBy, filterRate, filterCat, filterGenre, userId, seriesId, seasonId, searchTerms);
			});
			
			
			$('#pageButtons').undelegate();
			$('#pageButtons').delegate('a.navbuttons', 'click', function(){
			var $this = $(this),
            currentPage = parseInt($this.data('type'));
			
			//alert(currentPage);
			
            //$this.addClass('active').siblings().removeClass('active');
			endRange=currentPage*20;
			startRange=endRange-20;
			reloadGallery(requestType, startRange, endRange, sortBy, filterRate, filterCat, filterGenre, userId, seriesId, seasonId, searchTerms);

			});
			
		$('menu555').delegate('a.navbuttons444', 'click', function(){
			var $this = $(this),
				thisindex = $this.index('a.navbuttons'),
				sections = $('section.displayStyle');
				
			$this.addClass('active').siblings().removeClass('active');			
			
			
			
			if($this.parent().is('#sortButtons')) {   //code to sort the items
				var thumbFilteredData, coverFilteredData;
				if($this.data('type') === 'all') {
					thumbFilteredData = $thumbListClone.find('li');
		
				}
				else {
					thumbFilteredData = $thumbListClone.find('li[data-type='+ $this.data('type') +']');
				
				}				
				
				$thumbList.quicksand(thumbFilteredData, {
					duration: 800,
					adjustHeight: 'dynamic',
					useScaling: false
				}, function(){				
					$thumbList.css('height', 'auto');
					
					if( ie9js ) {   //reapply css styles when using IE9.js
						IE7.recalc();
					}
				});
				
				
			}
			else {   //code to display the items as thumbnails or in coverflow mode
				if( sections.eq(thisindex).is(':visible') ) {
					return false;
				}
				else {
					sections.filter(':visible').fadeOut(600, function(){
						sections.eq(thisindex).fadeIn(600);
					});
				}
			}
		});
		
		// handle overlay opening when clicking on thumbnails in #thumbGallery
		$thumbList.delegate('img', 'click', function(){
		//alert($(this).parent().data('type'));

			var $thisparent = $(this).parent(),
				type = $thisparent.data('type'),
				sources = $files.eq( $thisparent.data('id') - 1 ).find('source'),
				title1 = $files.eq( $thisparent.data('id') - 1 ).find('title').text(),
				desc = $files.eq( $thisparent.data('id') - 1 ).find('description').text(),
				series1 = $files.eq( $thisparent.data('id') - 1 ).find('seriesname').text(),
				price1 = $files.eq( $thisparent.data('id') - 1 ).find('price').text(),
				language1 = $files.eq( $thisparent.data('id') - 1 ).find('language').text(),
				user1 = $files.eq( $thisparent.data('id') - 1 ).find('user').text(),
				numratings1 = $files.eq( $thisparent.data('id') - 1 ).find('numratings').text(),
				category1 = $files.eq( $thisparent.data('id') - 1 ).find('category').text(),
				genre1 = $files.eq( $thisparent.data('id') - 1 ).find('genre').text(),
				seasonID1 = $files.eq( $thisparent.data('id') - 1 ).find('seasonID').text(),
				seriesID1 = $files.eq( $thisparent.data('id') - 1 ).find('seriesID').text(),
				duration1 = $files.eq( $thisparent.data('id') - 1 ).find('duration').text(),
				ratingimg1 = $files.eq( $thisparent.data('id') - 1 ).find('rating').text(),
				usrratingimg1 = $files.eq( $thisparent.data('id') - 1 ).find('ratingimg').text(),
				hdimg1 = $files.eq( $thisparent.data('id') - 1 ).find('hd').text(),
				vidid = $files.eq( $thisparent.data('id') - 1 ).find('videoID').text(),
				reqtype= $files.eq( $thisparent.data('id') - 1 ).find('request').text(),
				user2b= $files.eq( $thisparent.data('id') - 1 ).find('u').text();
		       
				allowdl = $files.eq( $thisparent.data('id') - 1 ).find('allowdl').text();
				rentactive = $files.eq( $thisparent.data('id') - 1 ).find('rentactive').text();
				seasonnum = $files.eq( $thisparent.data('id') - 1 ).find('seasonnum').text();
				
			
				
			if (rentactive!=''||user2b=='1'){
            document.location = webroot+siteroot+'?req=vid&id='+vidid;
            }else{			
			overlayCreate(type, sources, title1, desc, series1, price1, language1, user1, numratings1, category1, genre1, seasonID1, seriesID1, duration1, ratingimg1, usrratingimg1, hdimg1, vidid, rentactive, allowdl, seasonnum);
			}
		});
		
		
		
		
		/************* create overlay where large photo will be displayed or audio/video will be played ************/
		
		if ($('#overlay').length!=0){
		$('#overlay').remove();
		$('#overlayLoader').remove();
		$('#mask').remove();
		}	
		 
		 addoverlaydivs();
		   
		//function to insert overlay content	
		function overlayCreate(type, sources, title, description, series, price, language, user, numratings, category, genre, seasonID, seriesID, duration, ratingimg, usrratingimg, hdimg, vidid, rentactive, allowdl, seasonnum) {			
		
	var $curvidser;
	
		if (series.length>1){
		$curvidser=series;
		}else{
		$curvidser='Vidcano.com';
		}
		
		var $fintitle = htmlentities(title);
var $findesc = htmlentities(description);
var $finalser = htmlentities($curvidser);

  

var finalfburl = 'http://www.facebook.com/dialog/feed?app_id=107265222637432&link='+webroot+'?vid='+vidid+'&picture=http://c1385182.r82.cf0.rackcdn.com/'+vidid+'.1.jpg&name='+$fintitle+'&caption='+$finalser+'&description='+$findesc+'&message=From%20Vidcano.com&redirect_uri='+webroot+'?vid='+vidid;


$("#sharing #facebook_share").attr("href", finalfburl);

var finaltwitterurl = '<div id="twitter_div"><a id="twitter_play" href="http://twitter.com/share" class="twitter-share-button" data-url="'+webroot+'?vid='+vidid+'" data-count="vertical">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>';

$("#twitter_td").append(finaltwitterurl);

var embedlink = '<iframe width="480" height="270" src="'+webroot+'?req=embed&id='+vidid+'&w=270&h=480" frameborder="0"></iframe>';

$("#sharing #embed_link #textarea").text(embedlink);

		
var safeDesc = htmlentities(description);
		
		
		if ($('#overlay').length==0){
		addoverlaydivs();
		}
		
		
		
		$oinfo[0].innerHTML = '<table width="100%" border="0"><tr><td><h3>Duration</h3><td><h4>'+duration+'</h4></td><td><h3>Language</h3></td><td><h4>'+language+'</h4> <td><h3>Category</h3></td><td><h4>'+category+'</h4></td><td><h3>Genre</h3></td><td><h4>'+genre+'</h4></td></tr></table>';
		

		if (rentactive=='0'){
	    $orent[0].innerHTML = '<table width="100" border="0"><tr><td><a href="'+webroot+'?req=vid&id='+vidid+'"><img src="'+webroot+'images/rent.png" title="Click Here to Rent This Video"/></a><td><h4>&nbsp;$'+price+'</h4></td></tr></table> ';
	   
	   
		}else if (rentactive=='2'){
		 $orent[0].innerHTML = '<img id="actRental" src="'+webroot+'images/activate.png"/>';
		 $('#playerRent').css('left','370px');
		  $orent.delegate('img', 'click', function(){
				activateRental(vidid);	
		});
		 
		}else{
		if (allowdl=="1"){
		 $orent[0].innerHTML = '<img id=actDl src="'+webroot+'images/download.png"/>';

		  }else{
		   
		   $orent[0].innerHTML = '<table width="100" border="0"><tr><td><a href="'+webroot+'?req=vid&id='+vidid+'"><img src="'+webroot+'images/rent.png" title="Click Here to Rent This Video"/></a><td><h4>&nbsp;$'+price+'</h4></td></tr></table> ';
		  }
		}
		
		
		 $.cookie("curVars", description+'|'+duration+'|rent');
		
		if (series!=''){
			$otitle[0].innerHTML = '<a href="'+webroot+siteroot+'?req=series&id='+seriesID+'" title="'+series+'" style="color:#fff;">'+series+'</a>';
			
			if (seasonID!=0){
			$otitle[0].innerHTML += ' - <a href="'+webroot+siteroot+'?req=series&id='+seriesID+'-'+seasonID+'" title="Season '+seasonID+'" style="color:#fff;">Season '+seasonID+'</a>';
			}
			}else{
			$otitle[0].innerHTML = '';
			}
		
			$otitle2[0].innerHTML = '<a href="'+webroot+siteroot+'?req=vid&id='+vidid+'" title="'+title+'" style="color:#fff;">'+title+'</a>';
			$odescription[0].innerHTML = description;
			$ofirstimg[0].innerHTML = '<img src="'+ webroot + ratingimg +'" alt="Rating" />';
			
			
			if (hdimg){
			$ofirstimg[0].innerHTML += '<img src="'+ webroot + hdimg +'" alt="HD" />';
			}
			
			if (usrratingimg){
			$ofirstimg[0].innerHTML += '<img src="'+ webroot + usrratingimg +'" alt="Rating" /> <h3> ('+numratings+' Ratings)</h3>';
			}


			var top = $win.scrollTop() + $win.height()/2;
			
			$mask.css('height', $(document).height()).fadeIn(400, function(){
				$overlayLoader.css( 'top', top ).show();
				
	
					if( sources.eq(0).text().indexOf('youtube') !== -1 ) {
						var vId = sources.eq(0).text().split('v=')[1],
							video = '<iframe width="480" height="270" src="http://www.youtube.com/embed/'+ vId +'?rel=0" frameborder="0" allowfullscreen></iframe>';
							$overlayContent.append(video);
					}
					else if( sources.eq(0).text().indexOf('vimeo') !== -1) {
						var vId = sources.eq(0).text().split('/').pop(),
							video = '<iframe src="http://player.vimeo.com/video/'+ vId +'" width="480" height="270" frameborder="0"></iframe>';
							$overlayContent.append(video);
					}
					else {
						var video = '<video controls preload="auto" width="480" height="270">',
							safariVideo = '<video controls preload="auto" width="480" height="270"';
						
		
						for( var i = 0, len = sources.length; i < len; i++ ) {
							var filePath = sources.eq(i).text(),
							fileExt = filePath.split('.').pop();
							
							if( fileExt === 'mp4' ) {
								video += '<source type="video/mp4" src="http://c3332630.r30.cf0.rackcdn.com/'+vidid+'.samp.mp4" />';
								safariVideo += 'type="video/mp4" src="http://c3332630.r30.cf0.rackcdn.com/'+vidid+'.samp.mp4"></video>';
							}
							else if( fileExt === 'webm' ) {
								video += '<source type="video/webm" src="http://c3332630.r30.cf0.rackcdn.com/'+vidid+'.samp.webm" />';
							}
							else if( fileExt === 'ogv' ) {
								video += '<source type="video/ogg" src="http://c3332630.r30.cf0.rackcdn.com/'+vidid+'.samp.ogv" />';
							}
						}
						
						
						video += '</video>';
						
						if($.browser.safari) {  // Same Safari fix
							$overlayContent.append(safariVideo);
							
							$("#direct_link_player").live('click', function () {
		document.location=webroot+'?req=vid&id='+vidid;
return false;
		});
						}
						else {
							$overlayContent.append(innerShiv(video));
							$("#direct_link_player").live('click', function () {
		document.location=webroot+'?req=vid&id='+vidid;
return false;
		});
						}
					}
					
					overlayShow( 480, 400, top);
					
					
					
$('.jcart').submit(function(e) {
		//alert("added");
			add($(this));
			//e.preventDefault();
			return false;
		});						
				//}
			});
		
		}
		
		
		//function to position overlay and then show it
		function overlayShow( ow, oh, top ) {			
			var marginTop = -(oh + 40)/2,
				marginLeft = -(ow + 40)/2;
			
			$overlayLoader.hide();	
			$overlay.css({ width: ow, height: oh, top: top, marginTop: marginTop, marginLeft: marginLeft }).slideDown(600, function(){
				$overlayContent.fadeIn(400).find('audio,video').mediaelementplayer({
					success: function(mediaElement, domObject) {
				
				

$("#sharing #twitter_div").remove();


//$("#twitter_play").append(finaltwitterurl);


					
						if( ie9js ) {   //reapply css styles when using IE9.js
							meplayer = mediaElement;
							IE7.recalc();
						}
					}
				});
			});				
		}
		

		
		
	}  //end ccgallerySetup()
	
});  //end of document.ready()


