


var categoriesVideosArray = new Array();
var categoriesArray = new Array();
var loadedCategoriesIndex = 0;

function showVideos(categoryId, category)
{

	if(categoryId == selectedCategoryId){
		return;
	}
	if(selectedCategoryId)
	{
		var currCat = document.getElementById("category" + selectedCategoryId);
		if(currCat){
			currCat.className = "linkUnderlineHoverBlueBold";
		}
	}
	selectedCategoryId = categoryId;
	var newCat = document.getElementById("category" + categoryId);
	newCat.className = "videoItemSelectedBold";
	
	$("#current-videos").html("<img src='/images/loading.gif' style='padding-left:135px; padding-top:40px;' />");
	
    $.ajax({
      type: "GET",
      url: '/ajax/getVideosByCategoryId.php',
      data: {'category':categoryId},
      dataType:"html",
      success: function(videoItems) {
            $("#current-videos").html(videoItems).hide().fadeIn('slow');
      },
      error: function(msg) {
          // error
          alert("error"+msg);
      }
    });
}

function reloadAds(){

	var islandAdElem = document.getElementById("island-ad");
	var islandAdHTML = islandAdElem.innerHTML;
	islandAdElem.innerHTML = "";
	islandAdElem.innerHTML = islandAdHTML;
	
	var bannerElem = document.getElementById("video-banner-160-600");
	var bannerHTML = bannerElem.innerHTML;
	bannerElem.innerHTML = "";
	bannerElem.innerHTML = bannerHTML; 
	
}

function trackPage(videoId){
	try{
	document.getElementById("rating-frame").src = "video-rating-frame.php?id="+videoId;
	pageTracker._trackPageview("/video.php?id="+videoId);
	}
	catch(err){
		//alert(err.message);
	}
}

function playVideo(videoId){
	
	if(selectedVideoId){
        
        $("#videoTitle" + selectedVideoId).removeClass("videoItemSelectedBold");
        $("#videoTitle" + selectedVideoId).addClass("linkUnderlineHoverBlueBold");
        $("#videoSummary" + selectedVideoId).removeClass("videoItemSelected");
        $("#videoSummary" + selectedVideoId).addClass("linkUnderlineHoverBlue");
	}
	
	selectedVideoId = videoId;
	$("#videoTitle" + videoId).removeClass("linkUnderlineHoverBlueBold");
    $("#videoTitle" + videoId).addClass("videoItemSelectedBold");
    $("#videoSummary" + videoId).removeClass("linkUnderlineHoverBlue");
    $("#videoSummary" + videoId).addClass("videoItemSelected");
	
    $.ajax({
        type: "GET",
        url: '/ajax/getVideo.php',
        data: {'videoId':videoId},
        dataType:"json",
        success: function(video) {
            var url = video.url;
            var title = video.title;
            var summary = video.summary;
            var titleHtml = "<div id='video-title'>" + title + "</div>";
            $("#video-text").html(titleHtml).append("<p>"+summary+"</p>").hide().fadeIn('slow');
            var fileParam = "&file="+ url + "&autostart=true";
            s1.addParam('flashvars', fileParam);
            s1.write('player');
            setSocialUrls(video.id);
            doScroll();
            getVideoComments();
            trackPage(video.id);
            reloadAds();
      },
      error: function(msg) {
          alert("error");
      }
      });
}

function setSocialUrls(id) {
    if(id==undefined) {
        return;
    }
    var url = "www.surf2surf.com/video.php?id="+id;
    var tweetme = "<iframe scrolling='no' height='20' frameborder='0' width='90' src='http://api.tweetmeme.com/button.js?url=http://"+url+"&style=compact&amp;source=http://"+url+"'></iframe>";
    var fblike = "<iframe src='http://www.facebook.com/plugins/like.php?href="+url+"&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=21' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:21px;' allowTransparency='true'></iframe>";
    $("#tm_box").html(tweetme);
    $("#fbid").html(fblike);
}

function getVideoComments(){
	
    $.ajax({
        type: "GET",
        url: '/ajax/getVideoComments.php',
        data: {'videoId':selectedVideoId},
        dataType:"json",
        success: function(comments) {
            var commentsHtml = "";
			for(var i=0; i<comments.length;i++){
				var name = comments[i].name;
				var comment = comments[i].comment;
				var date = comments[i].date;
				var newDate = new Date(date);
				commentsHtml += createCommentDiv(name, comment, newDate)
			}
			$("#user-comments-container").html(commentsHtml).hide().fadeIn('slow');
        },
        error: function(msg) {
            alert("Error getting comments");
        }
    });

}

var scrollDelay;
function doScroll(){

	
	var top = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
	  //Netscape compliant
	  top = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	  //DOM compliant
	  top = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	  //IE6 standards compliant mode
	  top = document.documentElement.scrollTop;
	}
	
	
	if(top < 140){
		clearTimeout(scrollDelay);
		return;
	}
	
	var timeOut = 15;
	if(top < 180){
		timeOut = 30;
	}
	
	window.scrollBy(0,-5); 
    scrollDelay = setTimeout('doScroll()',timeOut);
}

function doComment()
{
    var name =  $("#name").val();
	var email = $("#email").val();
	var comment = $('#commentField').val();

    if(!validateFields(name, email, comment))
	{
		return;
	}

    $.ajax({
        type: "POST",
        url: '/ajax/addVideoComment.php',
        data: {'videoId':selectedVideoId, 'name=':name, 'email':email, 'comment':comment},
        success: function(comments) {
            $("#user-comments-container").append(createCommentDiv(name, comment, new Date()));
			$("#name").val("");
			$("#email").val("");
			$('#commentField').val("");
        },
        error: function(msg) {
            alert("Error posting comment");
        }
    });

}

function validateFields(name, email, comment)
{
	
	if(name == ''){
		alert('Please enter your Name');
		return false;
	}
	if(email == ''){
		alert('Please enter your Email');
		return false;
	}
	if (!((email.indexOf(".") > 2) && (email.indexOf("@") > 0))){
		alert("Please add a valid email address.")
		return false;
	}
	if(comment == ''){
		alert('Please enter your Comment');
		return false;
	}
	return true;
		
}


function createCommentDiv(name, comment, date){

	var months=new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

	var month = date.getMonth();
	var line1Str = months[month] + " " + date.getDate();
	
	var hour   = date.getHours();
	var minute = date.getMinutes();
	//var second = date.getSeconds();
	var ap = "am";
	if (hour   > 11) { ap = "pm";             }
	if (hour   > 12) { hour = hour - 12;      }
	if (hour   == 0) { hour = 12;             }
	if (hour   < 10) { hour   = "0" + hour;   }
	if (minute < 10) { minute = "0" + minute; }
	//if (second < 10) { second = "0" + second; }
	var timeString = hour +
	                 ':' +
	                 minute +
	  //               ':' +
	  //               second +
	                 " " +
	                 ap;

	
	var html = "<div id='comment-container'>" +
				"<div id='comment-date'>" +
					"<div id='cd-num'>"+ ++currentNumberOfComments +".</div><div id='cd-line1'>"+ line1Str + ",<br/>"+ date.getFullYear() + "</div>" +
					"<p id='cd-line2'>" + timeString + "</p>" +
				"</div>" +
				"<div id='comment2'>" +
					"<p>" + comment + "</p>" +  
					"<p id='comment-posted-by'>- Posted by <em>" + name + "</em> </p>" +
				"</div>" + 
				"</div>";
	
	//alert(html);	
	return html;
}

function showUploadWindow(){

	var myWindow = window.open('upload-youtube.php', "myWindow", "status=1,toolbar=0, menubar=0,width=400,height=400");
	myWindow.moveTo(400,100);
}



// Connect to Atlas adserver

// Page ID
apnpageNum = Math.round(Math.random() * 100000000000); /* need 12 digit for DoubleClick */

// bServer call 
function SetupAds(strSite,strArea,adArr,keyword){ 

    // Cache-busting and pageid value
    var aamRnd = Math.round(Math.random() * 100000000000);
    
    // Adserver URL
    adserver = "http://ads.apn.co.nz/bserver";
    
    // Ad tag targeting values which will be appended to each ad request section in the bserver ad call

    var site = strSite;
    var area = strArea;
    
    allAdTags = "/AAMALL/acc_random=" + aamRnd + "/pageid=" + apnpageNum + site + area + keyword; 

    //loop through adArr with all the ad call strings provided
    if(adArr.length > 0 && typeof(adArr[0]) != 'undefined'){
        
        var adStr = '';
        
        for(i=0;i<adArr.length;i++){
            
            adStr = adStr + adArr[i];
            
            
        }

        document.write('<SCR' + 'IPT SRC="' + adserver + allAdTags  + adStr + '?" type="text/JavaScript" language="JavaScript">');
        document.write('</SCR' + 'IPT>');
        
     }

}


function checkId (elementId)
{
	myObj = document.getElementById(elementId);
	if (myObj != null)
	// check the rendering divs before calling ads
{
		return true;
	}
	else
	{
		return false;
	}
}
