//
// Server Location.
//
var serverURL = 'http://www.cultureunplugged.com';
var favorites = {};
var watchlaterlist = {};
var watchLaterDropDown = null;
var myDiscoverDropdown = null;
var afterLogin = null;

function onScriptReady(){
	createDialog();
	createPopup();
	registerEvents();
	getUserInfo();
	getOtherBlogs();
	
	// register events
	$('#sideVisitHistory').bind('click',function(){
	 	location = serverURL + '/filmedia/findit.php#view=history';
	 	return false;
	});
}


if(!Array.indexOf){
	Array.prototype.indexOf = function(obj){
		for(var i=0; i<this.length; i++) { 
			if(this[i]==obj) return i; 
		} 
		return -1;
	}
}

function getDataFromServer(id, url, callback) {

    // Fetch the element pointed to by the id. If it exists, we destroy it so we can create a new one.
    var oScript = document.getElementById(id);

    // Point at the script tag, if it exists
    var head = document.getElementsByTagName("head").item(0);
     // Destroy the tag, if it exists
    if (oScript) {
		// Destory object
		head.removeChild(oScript);
    }
    // Create the new script tag
    oScript = document.createElement("script");

    // Setup the src attribute of the script tag
    oScript.setAttribute("src", url);

    // Set the id attribute of the script tag
    oScript.setAttribute("id",id);

    // Create the new script tag which causes the proxy to be called
    head.appendChild(oScript);
    // Asynchronous script tag properties -- a proprietary IE "feature"
    if ($.browser.msie) {
		if  (oScript.readyState == "loaded") {
			eval(callback);
			oScript.onreadystatechange = null;
		} else {
			oScript.onreadystatechange = function(){
				if (oScript.readyState == "loaded") {
					eval(callback);
					oScript.onreadystatechange = null;
				} 
			}
		}
    // All other web browsers just do the callback function
    } else {
       eval(callback);
    }
}

function setCUCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;

}

function showLoginForm(option)
{	
	if(typeof(option)!='undefined' && typeof(option.afterLogin)!='undefined') {
		afterLogin = option.afterLogin;
	}
	else {
		afterLogin = null;
	}
	
	showPopup({
		id: '#iframeLogin',
		url: serverURL + '/login',
		width: 554,
		height:272
	});
	
	setTimeout(function(){
		startCheckLogin();
	}, 1000);
	/*
	var url = serverURL + '/topdocumentaries/watch-online/filmedia/login.php?r='+escape(window.location.toString());
	if(option!=null){
		url += '&'+option;
	}
	window.location = url;
	*/
}

//
// user info
//
function getUserInfo()
{
	var id = 'getUserInfo';
	//var sendPath = encodeURIComponent('token='+readCookie('cu_sess_id'));
	var sendPath = 'token='+readCookie('cu_sess_id');
	var url = serverURL+'/xdscripts/getUserInfo.php?'+sendPath;
	getDataFromServer(id,url,'onGetUserInfo()');
}

function onGetUserInfo()
{
	if( (typeof userData)=='undefined' || userData==null ){
		setTimeout(onGetUserInfo, 500);
		return;
	}

	if(userData.isOK && userData.isLoggedIn){
		setUserData(userData);
		if(afterLogin!=null) {
			afterLogin();
			afterLogin = null;
		}
	}
}

function setUserData(_userData) {
	$('a.nav-login').unbind().removeAttr('rel').attr('href', serverURL + '/logout').html('Log Out');
	$('#welcome').find('a').unbind().attr('href',serverURL+'/profile.php').html('welcome, ' + _userData.autoName);
	$('.nav-my-discovery, .nav-watchlater-playlist').unbind();
	
	addWatchLaterDropdown();
	addMyDiscoveryDropdown();
	prePopulateCommentFields(_userData.autoName, _userData.email, _userData.url);
}

function isUserLoggedIn()
{
	return typeof (userData)!='undefined' && userData.isOK && userData.isLoggedIn;
}

function startCheckLogin() {
	if(!isPopupOpen)  {
		return;
	}
	
	
	$.ajax({
		url: serverURL + '/auth/check',
		dataType: 'jsonp',
		cache: false,
		success:function(res) {
			if(res.isOK==1) {
				/*
				userData = res.result;
				userData['isOK'] = true;
				userData['isLoggedIn'] = true;
				
				setUserData(res.result);
				*/
				setTimeout(function(){	
					userData = null;
					getUserInfo();
				},500)
				
				closePopup();
				//location.reload();
			}
			else {
				setTimeout(function(){
					startCheckLogin();
				},1000);
			}
		}
	});
}

//
// related forum
//
function getRelatedForum(categoryID) {
	var id = 'getRelatedForum';
	var sendPath = 'categoryID='+categoryID;
	var url = serverURL+'/xdscripts/getRelatedForum.php?'+sendPath;
	getDataFromServer(id,url,'onGetRelatedForum()');
}


function onGetRelatedForum() {
	if( (typeof relatedForum)=='undefined' ) {
		setTimeout(onGetRelatedForum, 500);
		return;
	}
	
	if(relatedForum.isOK){
		$('#relatedForumHeader').html( '<a href="'+relatedForum.link+'">'+relatedForum.header+'</a>' );
		$('#relatedForumDesc').html(relatedForum.description);
	}
}

function getRandomRelatedForum() {
	var id = getRandomBlogCategory();
	getRelatedForum(id);
}

//
// other blogs
//
function getOtherBlogs() {
	var id = 'getOtherBlogs';
	var sendPath = '';
	var url = serverURL+'/xdscripts/getOtherBlogs.php?'+sendPath;
	getDataFromServer(id,url,'onGetOtherBlogs()');
}

function onGetOtherBlogs() {
	if( (typeof otherBlogs)=='undefined' ) {
		setTimeout(onGetOtherBlogs, 500);
		return;
	}
	
	if(otherBlogs.isOK){
		for(var i=0;i< otherBlogs.result.length;i++){
			var blog = otherBlogs.result[i];
			
			var $div1 = $('<div class="other-blog-container"/>');
			var $div2 = $('<div class="other-blog-image"><a href="'+blog.link+'"><img src="'+blog.imageURL+'" alt=""/></a></div>');
			var $div3 = $('<div class="other-blog-desc"><h3 style="margin-bottom:5px"><a href="'+blog.link+'">'+blog.title+'</a>:</h3>'+blog.description+'</div>');
			$div1.append($div2);
			$div1.append($div3);
			
			$('#otherBlogsList').append($div1);
		}
	}
}

function showXDMenu(eventType, type)
{
	if( (typeof userData)=='undefined' ){
		setTimeout("showXDMenu('"+type+"')", 500);
		return;
	}
	
	if(!userData.isLoggedIn){
		if(eventType==1){
			showLoginForm();
		}
		return;
	}
	
	showMenu(type);	
}

function showXDJoinExperts() {
	/*if( (typeof userData)=='undefined' ){
		setTimeout("showXDJoinExperts()", 500);
		return;
	}
	
	if(!userData.isLoggedIn){
		showLoginForm();
		return;
	}
	*/
	//showJoinExperts();	
	window.location = serverURL + '/truthseekers/joindirectory';
	return true;
}

function showXDPostProjects() {
	if( (typeof userData)=='undefined' ){
		setTimeout("showXDPostProjects()", 500);
		return;
	}
	
	if(!userData.isLoggedIn){
		showLoginForm();
		return;
	}
	
	showPostProject(true);	
}

function prePopulateCommentFields(name, email, url)
{
	if($('#comment-author').length==1)
	{
		$('#comment-author').val(name);
		$('#comment-email').val(email);
		$('#comment-url').val(url);
	}
}


//
// rating
//
var cu_cr = 0, cu_cp, cu_rid = 'blogRating';
function setBlogRating(num, update) {
	var div = document.getElementById(cu_rid);
	if(div) {
		div.style.backgroundPosition = getBlogRatingPosition(num);
		var temp = cu_cr;
		cu_cr = num;
		if(num>0 && update) {
			updateBlogCookie(cu_cp, num);
			updateBlogRating(num);
			// average rating.
			var avgRating = Math.floor((temp*parseInt(bRating.numUsers)+parseInt(num))/(parseInt(bRating.numUsers)+1));
			setBlogRating(avgRating, false);
			bRating.enabled = false;
			
			alert("Thank you for rating this post.\nThe average rating is "+avgRating+".");
		}
	}
}
function updateBlogCookie(id, num) {
	var ck = readCookie('cu_blogRating');
	if(ck){
		var updated = false;
		var arr = ck.split('/');
		for(var i=0;i<arr.length;i++){
			var val = arr[i].split('.');
			if(val[0]==id){
				arr[i] = id+'.'+num;
				updated = true;
				break;
			}
		}
		
		var newVal = (updated) ? arr.join('/') : ck+'/'+id+'.'+num;
		setCUCookie('cu_blogRating',newVal, 365);
	}
	else {
		setCUCookie('cu_blogRating',id+'.'+num, 365);
	}
}
function checkBlogCookie(id) {
	var ck = readCookie('cu_blogRating');
	if(ck){
		var arr = ck.split('/');
		for(var i=0;i<arr.length;i++){
			var val = arr[i].split('.');
			if(val[0]==id){
				return val[1];
			}
		}
	}
	return -1;
}
function getBlogRatingPosition(num) {
	var x = 18*(num-5);
	return x+'px 0px';
}
function createBlogRating(id) {
	cu_rid = id;
	var div=document.getElementById(cu_rid);
	if(!div) return;
	
	var imgW=18, imgH=40;
	with(div.style) {
		backgroundImage = 'url('+serverURL+'/images/icon_blog_rating.gif)';
		backgroundRepeat = 'no-repeat';
		width = (imgW*5)+'px';
		height= imgH+'px';
	}
	for(var i=1;i<=5;i++){
		var img = new Image();
		img.src=serverURL+'/images/spacer.gif';
		img.style.width = imgW+'px';
		img.style.height=imgH+'px';
		img.setAttribute('num',i);
		if(bRating.enabled) {
			img.onmouseover = function() { if(bRating.enabled) div.style.backgroundPosition = getBlogRatingPosition(this.getAttribute('num')) }
			img.onmouseout = function() { if(bRating.enabled)  div.style.backgroundPosition = getBlogRatingPosition(cu_cr); }
		}
		img.onclick = function() { if(bRating.enabled) setBlogRating(this.getAttribute('num'),true); else alert('You have already rated this post.') }
		div.appendChild(img);
	}
}
function getBlogRating(rid)
{
	cu_rid = rid;
	cu_cp = window.location.toString().replace(/^.*\/([^\/]+)\.html$/,'$1');
	var rt = checkBlogCookie(cu_cp);
	var id = 'getBlogRating';
	var sendPath = 'rid='+cu_cp+'&rt='+rt;
	var url = serverURL+'/xdscripts/getBlogRating.php?'+sendPath;
	getDataFromServer(id,url,'onGetBlogRating()');
}

function onGetBlogRating() {
	if( (typeof bRating)=='undefined' ) {
		setTimeout(onGetBlogRating, 500);
		return;
	}
	if(bRating.isOK){
		createBlogRating(cu_rid);
		setBlogRating(Math.floor(bRating.rating), false);
	}
}

function updateBlogRating(rt){
	var id = 'updateBlogRating';
	var sendPath = 'rid='+cu_cp+'&rt='+rt;
	var url = serverURL+'/xdscripts/setBlogRating.php?'+sendPath;
	getDataFromServer(id,url,'onUpdateBlogRating()');
}

function onUpdateBlogRating(){
}

//
// blog quote
// 
function getBlogQuote(url) {
	var id = 'getBlogQuote';
	var sendPath = 'url='+escape(url);
	var url = serverURL+'/xdscripts/getBlogQuote.php?'+sendPath;
	getDataFromServer(id,url,'onGetBlogQuote()');
}

function onGetBlogQuote() {
	if( (typeof blogQuote)=='undefined' ) {
		setTimeout(onGetBlogQuote, 500);
		return;
	}
	
	if(blogQuote.isOK){
		$('#blog-quote').html(blogQuote.content).show();
	}
}


//
// about writer
//
function getAboutWriter(nickname) {
	var id = 'getAboutWriter';
	var sendPath = 'nickname='+escape(nickname);
	var url = serverURL+'/xdscripts/getAboutWriter.php?'+sendPath;
	getDataFromServer(id,url,'onGetAboutWriter()');
}

function onGetAboutWriter() {
	if( (typeof aboutWriter)=='undefined' ) {
		setTimeout(onGetAboutWriter, 500);
		return;
	}
	
	if(aboutWriter.isOK){
		$('#about-writer-profile').html(aboutWriter.content).show();
		$('#about-writer').show();
	}
}

//
// link tv list
//
function getLinkTVList() {
	var id = 'getLinkTVList';
	var url = serverURL+'/xdscripts/getLinkTVList.php';
	getDataFromServer(id,url,'onGetLinkTVList()');
}


function onGetLinkTVList() {
	if( (typeof linkTVList)=='undefined' ) {
		setTimeout(onGetLinkTVList, 500);
		return;
	}
	
	if(linkTVList.isOK){
		for(var i=0;i<linkTVList.movies.length;i++){
			var movie = linkTVList.movies[i];
			var div = document.createElement('div');
			div.innerHTML = movie.title+'<br/>'+
			                '<a href="'+movie.link+'">(view)</a>';
			document.getElementById('linkList').appendChild(div);
		}
	}
}

// common blog functions
function getRandomBlogCategory(){
	var urls = ['cultural_identity_what_defines_us','film_media_consciousness'];
	var index = Math.floor(Math.random()*100) % 2;
	return urls[index];
}

function fixCategoryName(){
	$('.lnk-cultural_identity_what_defines_us').each(function(){
		$(this).text('Cultural Identity');
	});
}


watchlaterlist = { 'responseText': '{"type":"watchlaterlist","result":[]}' };

//
// watch later dropdown
//
function addWatchLaterDropdown() {
	// create drop down list
	if(watchLaterDropDown==null) {
		watchLaterDropdown = $('<div class="dropdownlist"><ul></ul></div>').attr('id','watchlatermainmenu');
		$('.nav-watchlater-playlist').parent().append(watchLaterDropdown);				
	}
	
	var res = typeof(watchlaterlist.responseText)!='undefined' ? $.parseJSON(watchlaterlist.responseText) :  null;
	var items = (res==null) ? [] : res.result;
	
	$('a.nav-watchlater-playlist').parent().bind('click', function(e){
		return false;
	})
	.hover(
		function(){			
			// show list
			var item = watchLaterDropdown.find('ul li').length;
			
			if(item<1) {
				var $div = watchLaterDropdown.find('ul').eq(0);
				$div.find('li').remove();
				
				if(items.length>0) {
					for(var i=0;i<items.length;i++) {
						var data = items[i];
						$div.append('<li><a href="'+data.link+'" target="_blank">'+data.title+'</a></li>')
					}
					
					$div.append('<li class="favUpdate"><a href="'+serverURL+'/documentary/watch-online/festival/profile.php">UPDATE</a></li>');
				
					$div.find('li a').bind('click', function(e){
						location = $(this).attr('href');
						return true;
					});
				}
				else {
					$div.append('<li>You have no movies selected.</li>');									
				}
			}
			watchLaterDropdown.show();			
		},
		function() {
			// hide list
			watchLaterDropdown.hide();
		}
	);
}

//
// my discovery dropdown
//
function addMyDiscoveryDropdown() {
	if(myDiscoverDropdown==null) {
		myDiscoverDropdown = $('<div class="dropdownlist"><ul></ul></div>').attr('id', 'favoritesubmenu');
		var $list = myDiscoverDropdown.find('ul').eq(0);
		$list.append('<li class="discover-films"><a href="#">FILMS</a><ul class="submenu"></ul></li>');
		$list.append('<li class="discover-storyteller"><a href="#">STORY.TELLERS</a><ul class="submenu"></ul></li>');
		$('.nav-my-discovery').parent().append(myDiscoverDropdown);
		
		$list.find('li.discover-films a').bind('click', function(e) {
			var $li = $(this).parent();
			updateMyDiscoverList('film', $li);
			return false;
		});
		
		$list.find('li.discover-storyteller a').bind('click', function(e){
			var $li = $(this).parent();
			updateMyDiscoverList('storyteller', $li);
			return false;
		});
	}

	$('a.nav-my-discovery').parent().bind('click', function(e){
		return false;
	})
	.hover(
		function(){
			myDiscoverDropdown.show();
		},
		function() {
			// hide list
			myDiscoverDropdown.hide();
		}
	);	
}

function updateMyDiscoverList(type,$li) {			
	myDiscoverDropdown.find('.submenu').hide();
	$li.find('ul.submenu').eq(0).show();
	
	var $div = $li.find('ul.submenu').eq(0);
	$div.find('li').remove();
	var res = typeof(favorites[type].responseText)!='undefined' ? $.parseJSON(favorites[type].responseText) : null;
	var items = (res==null) ? [] : res.result;
	
	if(items.length>0) {
		for(var i=0;i<items.length;i++) {
			var data = items[i];
			$div.append('<li><a href="'+data.link+'">'+data.title+'</a></li>');
		}
		$div.append('<li class="favUpdate"><a href="'+serverURL+'/documentary/watch-online/festival/profile.php">UPDATE</a></li>');
		
		$div.find('li a').bind('click', function(e){
			location = $(this).attr('href');
			return true;
		});
	}
	else {
		$div.append('<li>No Entry</li>');
	}
	
	$div.show();
}

//
// dialog
//
// popup settings
var $dialog = null;

function createDialog() {
	$('body').append('<div id="dialog-popup"><div class="dialog-title"></div><div class="dialog-content"><iframe frameborder="0" allowTransparency="true"></iframe></div></div>');
	$dialog = $('#dialog-popup');
	$dialog.dialog({
		width: 486,
		height:'auto',
		minHeight: 360,
		modal: true,
		autoOpen: false,
		closeOnEscape: false,
		resizable: false,
		position:['center',150],
		zIndex: 9999,
		draggable: false,
		open: function(event,ui) {
			
		},
		close: function(event, ui) {
			$dialog.find('iframe').eq(0).attr('src',serverURL+'/popups/blank.html').hide();
		}
	});
}

function showDialog(config) {
	if(config.type=='iframe') {
		var $div = $dialog.find('iframe').eq(0);
		$div.attr('src', config.url);
		$div.width(config.width).height(config.height);
		$div.show();
	}
	var title = typeof(config.title)!='undefined' ? config.title : '';		
	var titleSlicePoint = 33;
	
	if(typeof(config.titleSlicePoint)!='undefined') {
		titleSlicePoint = parseInt(config.titleSlicePoint);
		if(titleSlicePoint<3) {
			titleSlicePoint = title.length;
		}
	}			
	
	if(title.length>titleSlicePoint) {
		title = title.substr(0,titleSlicePoint-3) + '...';
	}
	
	if(typeof(config.paddingLeft)!='undefined') {
		
		title = '<span style="padding-left:'+config.paddingLeft+'px">'+title+'</span>';
	}
	$dialog.find('.dialog-content').width(config.width).height(config.height);
	$dialog.dialog('option', 'title', title);
	$dialog.dialog('option', 'width', config.width);
	$dialog.dialog('option', 'height', config.height+36);
	//$dialog.parent().dialog('open');
	// fixed position.
	$dialog.parent().css({position:"fixed"}).end().dialog('open');
}

function closeDialog() {
	if($dialog) $dialog.dialog('close');
}

//
// popup
//
var $popup = null;
var $overlay = null
var $currentDivId = null;
var isPopupOpen = false;
function createPopup() {
	var $this = this;
	$('body').append('<div id="overlay"><div class="contentWrap"/></div><div id="tempOverlayDiv"/>');
	$popup = $('#overlay').find('div.contentWrap').eq(0);
	
	var triggers = $('#overlay').overlay({
		top: 'center',//'20%',
		mask: {
			color: '#111111',
			opacity: 0.75
		},
		closeOnClick: false,
		onClose: function(event) {
			isPopupOpen = false;
			$currentDivId = null;
			$popup.children().each(function(){
				$('#tempOverlayDiv').append($(this));
			});
			$('#overlay').removeClass();
		}
	});
	$overlay = triggers.eq(0).overlay();
}

function showPopup(options) {
	var divId = options.id,
	    href = options.url;		
		
	// ignore if there is no href assigned.
	if(href=='#' || href=='' || href==null) {
		return;
	}
	
	var $container = $popup;
	
	if(typeof(divId)=='undefined')
		return;
	
	var id    = divId.substring(1);
	var dimension = {
		width: options.width,
		height: options.height
	};
	
	isPopupOpen = true;
	$currentDivId = divId;
	$container.width(dimension.width).height(dimension.height);
	
	if($(divId).length>0) {
		$container.append($(divId));
		$overlay.load();
		return;
	}
	else {
		var id = divId.substring(1);
		var url = href, _ts = new Date().getTime();
		url += url.indexOf('?')!=-1 ? '&':'?';
		url += '_v='+ _ts;
		
		if(divId.search(/^#iframe/)!=-1) {		
			$container.append('<iframe id="'+id+'" name="'+id+'" src="'+url+'" frameborder="0" allowTransparency="true" style="position:absolute;left:0;top:0;overflow:hidden"></iframe>');		
			$(divId).width(dimension.width).height(dimension.height);
			$overlay.load();
		}
		else {
			$container.append('<div id="'+id+'"/>');
			$(divId).width(dimension.width).height(dimension.height);
			$.ajax({
				url: href,
				dataType: 'html',
				contentType: 'text/html;charset=utf-8',
				success: function(data) {
					$(divId).html(data);
					$overlay.load();
				}
			});
		}
	}
}

function closePopup()
{
	isPopupOpen = false;
	$overlay.close();
	$('#overlay').hide();	
}

// 
//
//
function showPostProject()
{
	if(isUserLoggedIn()) {
		showDialog({
			title: 'POST FILM/MEDIA PROJECT:',
			type: 'iframe',
			url: serverURL + '/popups/filmedia/postProject.php',
			width: 607,
			height: 760,
			paddingLeft: 34
		});
	}
	else {
		;
		showLoginForm({
			afterLogin: showPostProject
		});
	}
}

//
// click events
//
function registerEvents() {
	$('a.nav-report-bug').bind("click",function(){
		showDialog({
			title: 'REPORT PROBLEM:',
			type: 'iframe',
			url: serverURL + '/popups/filmedia/reportProblem.php',
			width: 338,
			height: 440,
			paddingLeft: 25
		});
		return false;
	});
	
	$('.nav-collaborate').find('a').bind('click', function(){
		showPostProject();
		return false;
	});
	
	$('#welcome a, a.nav-login').bind('click',function(){
		showLoginForm();
		return false;
	});
	
	if(!isUserLoggedIn()) {
		$('.nav-my-discovery, .nav-watchlater-playlist').bind('click',function(){
			showLoginForm();
			return false;	
		});
	}
}

