var site = 'http://videos.zdnet.co.uk/';
var sitename = 'ZDNet UK videos';
var debug = false;

var current_video = null;
var current_tab = null;
var current_franchise = null;
var parent_type = 'story';
var firstload = true;


function hidePlaylist() {
	if (debug) alert('Debugging information:' + "\n\n" + 'hidePlaylist(); called');
	var div = document.getElementById('ab_playlist_div');
	var tab = document.getElementById('ab_playlist_tab');
	if (tab && div) {
		div.style.height = '0px';
		tab.className = '';
	}
	return(true);
}

function addMedia(id, now) {
	if (debug) alert('Debugging information:' + "\n\n" + 'addMedia(' + id + ', ' + (now ? 'true' : 'false') + '); called');
	var videoPlayer = document.getElementById('player');
	videoPlayer.addMedia(id, now);
		return(true);
}

function updateVideoPageLivery(id, title, franchise, embeddable, attempts) {
	if (attempts > 30) {
		alert('The video is having trouble communicating with the rest of the webpage. This page may appear incomplete. This can happen when the page has taken a long time load, such as a slow connection or when there are many server requests.');
	} else {
		if (document.getElementById('dyn') && updateVideoPageLivery2) {
			updateVideoPageLivery2(id, title, franchise, embeddable);
		} else {
			attempts++;
			setTimeout('updateVideoPageLivery(' + id + ', \'' + title + '\', ' + franchise + ', ' + (embeddable ? 'true' : 'false') + ', ' +  attempts + ');', 1000);
			return(true);
		}
	}
}

function updateVideoPageLivery2(id, title, franchise, embeddable) {
	if (debug) alert('Debugging information:' + "\n\n" + 'updateVideoPageLivery2(' + id + ', \'' + title + '\', ' + franchise + ', ' + (embeddable ? 'true' : 'false') + '); called');

	if (firstload) {
		ajaxLoadTab(onloadtab.tab, onloadtab.sort, onloadtab.page, onloadtab.franchise, onloadtab.search);
		firstload = false;
	} else if (current_tab == 'playing' && franchise != current_franchise) {
		ajaxLoadTab(null, null, null, franchise, null);
	}
	current_video = id;
	current_franchise = franchise;
	
	ajaxLoadInfo(id);
		
	parent_id = id;
	ajaxCommentGetList();

	var url = site + id + '.htm';
	var url_escaped = encodeURIComponent(url).replace(/%20/g, '+');
	var title_escaped = encodeURIComponent(title).replace(/%20/g, '+');

	var share_delicious = document.getElementById('share_delicious');
	if (share_delicious) share_delicious.href = 'http://del.icio.us/post?title=' + title_escaped + '&url=' + url_escaped;

	var share_digg = document.getElementById('share_digg');
	if (share_digg) share_digg.href = 'http://www.digg.com/submit?phase=2&url=' + url_escaped + '&title=' + title_escaped + '&media=video';
	
	var share_facebook = document.getElementById('share_facebook');
	if (share_facebook) share_facebook.href = 'http://www.facebook.com/share.php?u=' + url_escaped + '&t=' + title_escaped;

	var share_slashdot = document.getElementById('share_slashdot');
	if (share_slashdot) share_slashdot.href = 'http://slashdot.org/slashdot-it.pl?op=basic&url=' + url_escaped;

	var share_stumbleupon = document.getElementById('share_stumbleupon');
	if (share_stumbleupon) share_stumbleupon.href = 'http://www.stumbleupon.com/submit?title=' + title_escaped + '&url=' + url_escaped;
	
	var contents_getlink = document.getElementById('contents_getlink');
	if (contents_getlink) contents_getlink.value = url;

	var contents_embed = document.getElementById('contents_embed');
	var ab_embed_tab = document.getElementById('ab_embed_tab');
	if (embeddable && contents_embed && ab_embed_tab) {
		contents_embed.value = '<!-- Start CBS Interactive Embeded Player --><div style="width: 400px; overflow: hidden;"><object type="application/x-shockwave-flash" data="' + site + 'embed/' + id + '" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="400" height="265" allowfullscreen="true"><param name="allowScriptAccess" value="always" /><param name="movie" value="' + site + 'embed/' + id + '" /><param name="loop" value="false" /><param name="allowFullScreen" value="true" /><param name="quality" value="high" /><param name="bgcolor" value="#dddddd" /></object><div style="width: 400px; height: 26px; background-color: #dddddd; overflow: hidden;"><ul style="text-align: left; margin: 5px 0; padding: 2px; font-size: 10px; font-family: arial; color: #999;"><li style="list-style: none; float: left; margin-right: 5px;"><a href="' + site + id + '.htm" style="color: #fff; display: inline;">' + title + '</a></li><li style="list-style: none; float: left; margin-right: 5px;"><strong>|</strong></li><li style="list-style: none; float: left;"><a href="' + site + '" style="color: #ffffff; display: inline;">' + sitename + '</a></li></ul></div></div><!-- Finish CBS Interactive Embeded Player -->';
		ab_embed_tab.style.display = 'block';
	} else {
		contents_embed.value = '';
		ab_embed_tab.style.display = 'none';
	}
	return(true);
	
}

// Tab panel

var ajax_tab = new sack();

function ajaxTabLoading() {	
	if (debug) alert('Debugging information:' + "\n\n" + 'ajaxTabLoading(); called');
	var tabdiv = document.getElementById('dyn');	
	if (tabdiv) {
		removeChildNodes(tabdiv);
		var div = createTag('div', null, { 'align' : 'center' })
		div.appendChild(createTag('br'));
		div.appendChild(createTag('br'));
		div.appendChild(createTag('img', null, { 'src' : 'http://videos.zdnet.co.uk/i/videos/ico-ajax-cog.gif'}));
		div.appendChild(createTag('p', 'Fetching list of videos...'));
		div.appendChild(createTag('br'));
		tabdiv.appendChild(div);
	}
	return(true);
}

function ajaxTabCompleted() {
	if (debug) alert('Debugging information:' + "\n\n" + 'ajaxTabCompleted(); called');
	var dyn = document.getElementById('dyn');
	if (dyn) dyn.innerHTML = ajax_tab.response;
	return(true);
}

function ajaxLoadTab(tab, sort, page, franchise, search) {
	if (debug) alert('Debugging information:' + "\n\n" + 'ajaxLoadTab(' + tab + ', ' + sort + ', ' + page + ', ' + franchise + ', ' + search + '); called');
	current_tab = (tab ? tab : current_tab);
	
	var tabs = new Array('playing', 'top', 'all', 'advertiser', 'search');
	for (i = 0; i < tabs.length; i++) {
		tabdiv = document.getElementById('tab-' + tabs[i]);
		if (tabdiv) {
			if (current_tab == tabs[i]) {	
				check_selected = new RegExp('\\b'+'selected'+'\\b').test(tabdiv.className);	
				if (!check_selected) {
					tabdiv.className = 'selected ' + tabdiv.className;
				}
			} else {				
				tabdiv.className = tabdiv.className.replace(/selected/i, '');
			}
		}
	}
	ajax_tab.resetData();
   	ajax_tab.setVar('tab', (current_tab ? current_tab : ''));
   	ajax_tab.setVar('sort', (sort ? sort : ''));
   	ajax_tab.setVar('page', (page ? page : ''));
   	ajax_tab.setVar('franchise', (current_tab == 'playing' && current_franchise ? current_franchise : (franchise ? franchise : '')));
   	ajax_tab.setVar('search', (search ? search : ''));
	ajax_tab.requestFile = '/ajax-tab.htm';
   	ajax_tab.onLoading = ajaxTabLoading;
   	ajax_tab.onCompletion = ajaxTabCompleted;
  	ajax_tab.runAJAX();
	//return(true);
}


// Video info panel

var ajax_info = new sack();

function ajaxInfoLoading() {
	if (debug) alert('Debugging information:' + "\n\n" + 'ajaxInfoLoading(); called');
	var info = document.getElementById('infoBox');
	if (info) {
		removeChildNodes(info);
		var div = createTag('div', null, { 'align' : 'center' })
		div.appendChild(createTag('br'));
		div.appendChild(createTag('br'));
		div.appendChild(createTag('img', null, { 'src' : 'http://videos.zdnet.co.uk/i/videos/ico-ajax-cog.gif'}));
		div.appendChild(createTag('p', 'Fetching info for this video...'));
		div.appendChild(createTag('br'));
		info.appendChild(div);
	}
	return(true);
}

function ajaxInfoCompleted() {
	if (debug) alert('Debugging information:' + "\n\n" + 'ajaxInfoCompleted(); called');
	document.getElementById('infoBox').innerHTML = ajax_info.response;
	return(true);
}


function ajaxLoadInfo(id) {
	if (debug) alert('Debugging information:' + "\n\n" + 'ajaxLoadInfo(' + id + '); called');
	ajax_info.resetData();
	ajax_info.setVar('id', id);	
	ajax_info.requestFile = '/ajax-videoinfo.htm';
	ajax_info.onLoading = ajaxInfoLoading;
	ajax_info.onCompletion = ajaxInfoCompleted;
	ajax_info.runAJAX();
	return(true);
}



// Comments panel


var ajax_comment = new sack();
var message_fetching_comment = 'Fetching comment list please wait...';

function ajaxCommentLoading() {
	if (debug) alert('Debugging information:' + "\n\n" + 'ajaxCommentLoading(); called');
	var e = document.getElementById('commalert_comments_div');
	removeChildNodes(e);
	var div = createTag('div', null, { 'align' : 'center' });
	div.appendChild(createTag('img', null, { 'src' : '/i/ajax-loader.gif'}));
	div.appendChild(createTag('p', message_fetching_comment));
	e.appendChild(div);
	return(true);
}

function ajaxCommentCompleted() {
	var comment_listing;
	if (debug) alert('Debugging information:' + "\n\n" + 'ajaxCommentCompleted(); called');
	var e = document.getElementById('commalert_comments_div');
	if (e) {
		removeChildNodes(e);
		var response = eval('(' + ajax_comment.response + ')');
		if ((response.comments) && typeof(response.comments.length) == 'number' && response.comments.length > 0) {
			var div_comment = "";
			for (var n = 0; n < response.comments.length; n++) {
				var comment = response.comments[n];
				div_comment += "\n\n" +
				"<div class=\"commentpost\">\n<div class=\"commentcontent\">" +
				"\t<img height=\"36\" width=\"36\" alt=\"AVATAR: user avatar\" src=\"" + comment.AVATAR_URL + "\" class=\"ava\"/>" +
				"<p><strong>" + comment.SUBJECT + "</strong></p>" +
				"\t<p>" + comment.COMMENTS + "</p></div>" +
				"\t<div class=\"commentInfo clearfix\">"  +
							"\n\t<p class=\"userInfo\">Updated by <a href=\"" + comment.MEMBER_PROFILE_URL + "\" class=\"userLink\">" + comment.FULLNAME + "</a> <span> on " + comment.FORMATTED_DATE + "</span></p>" +
							"\n\t<p class=\"replybutton\"><a href=\"" + comment.REPLY_URL + "#reply\">Post a comment</a></p>" +
						"\n</div>" +
				"\n</div>\n";
			}
			div_comment += "\n<div class=\"commentpost entry clearfix\">\n";						
			div_comment += "\t<a href=\"" +  response.comment_url +  "\" class=\"submitComment\">Post a comment</a>\n";								
			div_comment += "</div>\n";
			e.innerHTML =  "<div class=\"primary\">" + div_comment + "</div>";
			// alert(e.innerHTML);"
		} else {
			if (response.story_attached){
			comment_listing = "<div class=\"commentpost entry clearfix\"><p> Be the first to comment on this ";
			if ( parent_type == 'story' ) {
				comment_listing += " story";
			} else if  (parent_type == 'video') {
				comment_listing += " video";
			}
			comment_listing += "\n<div class=\"commentpost entry clearfix\">\n";						
			comment_listing += "\t<a href=\"" +  response.comment_url +  "\" class=\"submitComment\">Post a comment</a>\n";								
			comment_listing += "</div>\n";
			comment_listing += ".</p></div>";
			e.innerHTML = comment_listing;
			}
		}
								
	}
	return(true);
}

function ajaxCommentAlert(text, append) {
	if (debug) alert('Debugging information:' + "\n\n" + 'ajaxCommentAlert(' + text + '); called');
	var alert = document.getElementById('alert');
	if (typeof(text) == 'string' && text.length) {
		if (append) {
			alert.innerHTML += text + '<br>\n';
		} else {
			alert.innerHTML = text + '<br>\n';
		}
		alert.style.display = 'block';
	} else {
		alert.innerHTML = "";
		alert.style.display = 'none';
	}
	return(true);
}

function ajaxCommentInitVars() {
	if (typeof(ajax_comment) == 'object') {
		ajax_comment.resetData();
		ajax_comment.setVar('id', parent_id);
		ajax_comment.setVar('type', parent_type);
	 	ajax_comment.method = "post";
	   	ajax_comment.onLoading = ajaxCommentLoading;
    		ajax_comment.onCompletion = ajaxCommentCompleted;    		
	    	ajax_comment.requestFile = '/ajax-comments.htm';
	}
}

function ajaxCommentGetList(_parent_id) {
	if (typeof(ajax_comment) == 'object') {		
		ajaxCommentInitVars();
		if (_parent_id) {
			ajax_comment.setVar('id', _parent_id);
		}
	    	ajax_comment.runAJAX();
	}
	return true;
}

function ajaxCommentValidate() {
	var is_valid = true;
	ajaxCommentAlert('', false);
	formElement = document.getElementById('addComment');
	for(var i = 0; i < formElement.elements.length; i++)
	{
		input = formElement.elements[i];
		input.className = "";
		if ( input.name == 'comments') {
			if (input.value == "") {
				if (member_login) {
					ajaxCommentAlert(message_user_missing_comments, true);
				} else {
					ajaxCommentAlert(message_anon_missing_fields, true);
				}
				input.className = 'userError';
				is_valid = false;
				break;
			}
		}
		// Email is required for non logged in user
		if (input.name == 'comment_email') {
			if (formElement.elements[i].value == "") {
				ajaxCommentAlert(message_anon_missing_fields, true);
				input.className = 'userError';
				is_valid = false;
				break;				
			} else if ( !validateEmail(input.value)) {
				ajaxCommentAlert(message_wrong_email, true);
				input.className = 'userError';
				is_valid = false;
				break;				
			}
		}
		if (input.name == 'CAPTCHA') {
			if ( input.value.length != 6 ) {
				ajaxCommentAlert(message_wrong_captcha, true);
				input.className = 'userError';
				is_valid = false;
				break;				
			}
		}
	}
	return is_valid;
}


if (debug) { alert('Debugging information: javascript loaded okay'); }
