
///////////////////////////////////////
// GLOBAL FLASH CALLBACKS FUNCTIONS ///
///////////////////////////////////////

// inside DOM - function names
var changeStatus;
var clearPlaylist;
var output;
var removeFromPlaylist;

// outside callbacks
function __changeStatus(mediaidlong, mediaid, medtitle, meddescription, medurl, medimage, medialength, views, mediadate, votes){
	//alert('called');
	changeStatus(mediaidlong, mediaid, medtitle, meddescription, medurl, medimage, medialength, views, mediadate, votes);
}

function __removeFromPlaylist(mediaid){
	removeFromPlaylist(mediaid);	
}

function _clearAll(){
			clearPlaylist('flash');		
}

//debugging
function __output(msg)
{
	alert(msg);	
}

///////////////////////////////////////

// JavaScript Document
window.addEvent('domready', function() {
									 
new SmoothScroll({ duration: 1800 });

var sessionId = '';
var tempId = '9d966558-a6b3-404c-8336-c53ee459ac8b';
var tempRss = 'http://feed.viostream.com/1fa74015-b2d9-492b-8205-193fe7562d43';
var tempSelectClass = 'general';
var tempInd = 1;
var tempSort = 'DateAdded';
var defSort = 'DateAdded';
var tempSearch = '';
var tempsearchPageInd = 0;
var previousNowplaying = '';
var initScript = 1;

var playlistId = '';
var addplayEvent;

var pageStarted = 1;
var qpageLoad = 0;



// click events for all main categories
//$('careers').addEvent('click', function(){categoryGet('e5715792-ea26-4a5a-b38a-82ddeeb6d0cd'); showDivSetClass($('careers').get('id'),($('careers').getParent()).get('id'));});
//$('careers').addEvents({'click': function(){categoryGet('e5715792-ea26-4a5a-b38a-82ddeeb6d0cd'); showDivSetClass('careers','maincategories','');}, 'mouseover': function(){ alert('over'); }});
$('careers').addEvents({'click': function(event){ event.stop();categoryGet('e5715792-ea26-4a5a-b38a-82ddeeb6d0cd', 'http://feed.viostream.com/c03a1f97-1c58-48e4-841f-f25e9ce9a822'); showDivSetClass('careers','maincategories','');}});
$('services').addEvent('click', function(event){ event.stop(); categoryGet('13173193-edc5-4ce7-8b27-d3c25a8cf3cc', 'http://feed.viostream.com/cce847ff-449f-442d-94f9-cd4f0371c602'); showDivSetClass('services','maincategories','');});
$('inspiring').addEvent('click', function(event){ event.stop();categoryGet('9deb9c4c-331a-4ef8-b216-8e8cd3d6bb99', 'http://feed.viostream.com/8964c6b0-8474-451b-a79f-c6ebbeddea46'); showDivSetClass('inspiring','maincategories','');});
$('leadership').addEvent('click', function(event){ event.stop();categoryGet('5b081584-2114-4718-84ea-65ae88b54002', 'http://feed.viostream.com/5c2507d7-e407-4385-9124-ab68789ad647'); showDivSetClass('leadership','maincategories','');});
$('innovation').addEvent('click', function(event){ event.stop();categoryGet('0662f058-1969-434c-8759-a9d52953289f', 'http://feed.viostream.com/26f67ddb-9f31-4cef-a63e-b57cbc431f17'); showDivSetClass('innovation','maincategories','');});
$('foundation').addEvent('click', function(event){ event.stop();categoryGet('7c5765ba-ddb2-4c51-a101-687707c31513', 'http://feed.viostream.com/03ef13ba-3fa9-467b-b3c4-16cfee8f6b9a'); showDivSetClass('foundation','maincategories','');});
$('general').addEvent('click', function(event){ event.stop();categoryGet('9d966558-a6b3-404c-8336-c53ee459ac8b', 'http://feed.viostream.com/1fa74015-b2d9-492b-8205-193fe7562d43'); showDivSetClass('general','maincategories','');});

// click events for playlist categories
//$('playing').addEvent('click', function(){showDivSetClass($('playing').get('id'),($('playing').getParent()).get('id'));});
$('playing').addEvent('click', function(event){ event.stop();showDivSetClass('playing','playercategories','playingcontent');});
$('playlist').addEvent('click', function(event){ event.stop();showDivSetClass('playlist','playercategories','playlistcontent');});
//$('comments').addEvent('click', function(){showDivSetClass('comments','playercategories', 'commentcontent');});

// click events for sorting the media 
$('DateAdded').addEvent('click', function(){categoryGetMedia('',1,'DateAdded')});
$('Alphabetical').addEvent('click', function(){categoryGetMedia('',1,'Alphabetical')});
$('Views').addEvent('click', function(){categoryGetMedia('',1,'Views')});
$('Rating').addEvent('click', function(){categoryGetMedia('',1,'Rating')});

//top nav links
$('logo').addEvent('click', function(){	window.open('http://www.deloitte.com.au','Deloitte','');	});
$('loginnav').addEvent('click', function(){document.location.href = 'http://deloittetv.deloitte.com.au';});

$('clearplaylist').addEvent('click', function(){clearPlaylist('javascript')});

$('submitsearch').addEvent('click', function(){searchMedia();});

$('search1').addEvent('keydown', function(event){
    if (event.key == "enter") searchMedia();
});


$('nextbutton').addEvent('click', function(){categoryGetMedia('',tempInd+1,tempSort)});
$('previousbutton').addEvent('click', function(){categoryGetMedia('',tempInd-1,tempSort);});


function updatePage(totalpages, currentpage) {

	$('paginationtext').set('html', 'Page '+currentpage+' of '+totalpages);
}

//QUERY STRING READER////
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

var qmedid = gup( 'mediaId' );

function getVidFromQuery () {
	//mediaId='+mediaid+'&medtitle='+medtitle+'&meddescription='+escape(meddescription)+'&medurl='+medurl+'&medimage='+medimage+'&duration='+medialength+'&viewcount='+views+'&created='+mediadate+'&votes='+votes+'
	var qmedid = gup( 'mediaId' );
/*	var qtitle = gup( 'medtitle' );
	var qdesc = gup( 'meddescription' );
	var qurl = gup( 'medurl' );
	var qimg = gup( 'medimage' );
	var qdur = gup( 'duration' );
	var qview = gup( 'viewcount' );
	var qcreate = gup( 'created' );
	var qvote = gup( 'votes' );*/
	
	
	
	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/MediaGet.php',
			onRequest: function() {
				//displayloader
			
			},
			onComplete: function(jsonObj) {
	
				if(jsonObj['result'] == 'failed'){
					alert('failed');

				} else {
					//alert('here');
/*					alert(jsonObj.MediaGetResult.Item.MediaBase.MediaDescription);
					alert(jsonObj.MediaGetResult.Item.MediaBase.MediaUrls.MediaUrl[1].Url);
					alert(jsonObj.MediaGetResult.Item.MediaBase.Thumbnails.Thumbnail.Path);
					alert(jsonObj.MediaGetResult.Item.MediaBase.MediaUrls.MediaUrl[1].Duration);
					alert(jsonObj.MediaGetResult.Item.MediaBase.ViewCount);
					alert(jsonObj.MediaGetResult.Item.MediaBase.Created);
					alert(jsonObj.MediaGetResult.Item.MediaBase.MediaTitle);
					alert(jsonObj.MediaGetResult.Item.MediaBase.AverageVotes);
					alert(jsonObj.MediaGetResult.Item.MediaBase.MediaId);*/
					
					
					var qdesc = jsonObj.MediaGetResult.Item.MediaBase.MediaDescription;
					var qurl = jsonObj.MediaGetResult.Item.MediaBase.MediaUrls.MediaUrl[1].Url;
					var qimg = jsonObj.MediaGetResult.Item.MediaBase.Thumbnails.Thumbnail.Path;
					var qdur = jsonObj.MediaGetResult.Item.MediaBase.MediaUrls.MediaUrl[1].Duration;
					var qview = jsonObj.MediaGetResult.Item.MediaBase.ViewCount;
					var qcreate = jsonObj.MediaGetResult.Item.MediaBase.Created;
					var qtitle = jsonObj.MediaGetResult.Item.MediaBase.MediaTitle;
					var qvote = jsonObj.MediaGetResult.Item.MediaBase.AverageVotes;
					
					//
					
					addtoplayList(unescape(qmedid), true, unescape(qtitle), unescape(qdesc), unescape(qurl), unescape(qimg), unescape(qdur), unescape(qview), unescape(qcreate),unescape(qvote));
		showDivSetClass('playing','playercategories','playingcontent');  // Play and send media id

				}
				
				
			}
		}).send('mediaId='+qmedid);
	
		


	
}

var loadMediaForCat= function(MediaBase) {

		$('allmediacont').empty();
	//	alert('1');
		var count = 0;
		var rowcount = 0;
		var margin;
		
		var mediaId;
		var title;
		var description;
		var videoURL;
		var thumbURL;
		var duration;
		var viewcount;
		var created;
		var votes;
		
		
		
		if(MediaBase.length==undefined)
		{
				mediaId = MediaBase.MediaId;
				title = MediaBase.MediaTitle;
				description = MediaBase.MediaDescription;
				videoURL = MediaBase.MediaUrls.MediaUrl[1].Url;
				thumbURL = MediaBase.Thumbnails.Thumbnail.Path;
				duration = MediaBase.MediaUrls.MediaUrl[1].Duration;
				viewcount = MediaBase.ViewCount;
				created = MediaBase.Created;
				votes = MediaBase.AverageVotes;
			
			count = formatGrid(mediaId,title,description,videoURL,thumbURL,duration,viewcount,created,votes,count,rowcount,margin);
		}
			else
		{
		
			MediaBase.each(function(media) {								
			
				mediaId = media.MediaId;
				title = media.MediaTitle;
				description = media.MediaDescription;
				videoURL = media.MediaUrls.MediaUrl[1].Url;
				thumbURL = media.Thumbnails.Thumbnail.Path;
				duration = media.MediaUrls.MediaUrl[1].Duration;
				viewcount = media.ViewCount;
				created = media.Created;
				votes = media.AverageVotes;
				
	//alert(mediaId);
				count = formatGrid(mediaId,title,description,videoURL,thumbURL,duration,viewcount,created,votes,count,rowcount,margin);
	
		
				rowcount++;
				
			
			});
		
		}
		

		$('allmediacont').fancyShow();
		$('allmediacont_loader').fancyHide();
		
	
}


var formatGrid = function(mediaId,title,description,videoURL,thumbURL,duration,viewcount,created,votes,count,rowcount,margin)
{
			
		
			if(count==1 || count == 4){		  
				var el = new Element('div', {'styles': {'margin-right': '16px' ,'margin-left': '16px', 'margin-bottom': '20px' , 'float':'left', 'width':'199px', 'background-image':'url(images/media_bg.jpg)','background-repeat':'no-repeat', 'height':'195px'}})
				count++; 
			}else{ 
				var el = new Element('div', {'styles': {'float':'left', 'width':'199px', 'height':'195px', 'margin-bottom': '20px', 'background-image':'url(images/media_bg.jpg)','background-repeat':'no-repeat'}});
				count++; 
			}	
			var imgcont = new Element('div', {'styles': {'width':'192px', 'margin-left':'1px', 'margin-top':'1px', 'cursor':'pointer'}, 
									  'events': {'click': function() { addtoplayList(mediaId, true, title, description, videoURL, thumbURL, duration, viewcount, created, votes); showDivSetClass('playing','playercategories','playingcontent'); }} // Play and send media id
									   });
			

			var thumb = new Element('img', {'src': thumbURL,'width':'192px','height':'105px',
									'styles': {'width':'192px', 'height':'105px'}
									}).inject(imgcont);
			
			imgcont.inject(el);
			
			var cleardiv = new Element('div', {'class':'clear'}).inject(imgcont, 'after');
			var para = new Element('div', {'styles': {'width':'192px', 'height':'85px', 'margin-left':'1px', 'margin-top':'1px', 'overflow':'hidden', 'cursor':'pointer'}, 
									   'events': {'click': function() { addtoplayList(mediaId, true, title, description, videoURL, thumbURL, duration, viewcount, created, votes); showDivSetClass('playing','playercategories','playingcontent'); }} // Play and send media id
									   }).inject(cleardiv, 'after');
			
		//	alert(title.length);
			if(title.length > 53) {  var titleshort = title.substring(0,53)+"..."; } else {  var titleshort = title; }
			// titleshort = title.substring(0,50)+'...'; 
			var name = new Element('h2', {'html': titleshort, 'class':'videotitle'}).inject(para);
			
			//alert('mediaforcat');
			var ratediv = new Element('div', {'styles': {'padding-left':'10px', 'padding-top':'10px' }}).inject(name, 'before');
					

			var imgdiv = new Element('div', {'id': 'star-'+mediaId,'styles': {'float':'left', 'margin-right':'5px'}}).inject(ratediv);
			//get star rating
			ratingGet(imgdiv,mediaId);			
			
			var viewdiv = new Element('div', {'styles': {'float':'left', 'padding':'4px'}}).inject(imgdiv, 'after');
			var spanview = new Element('span', {'html': viewcount+' views', 'class':'viewcount'}).inject(viewdiv);
			var cleardiv2 = new Element('div', {'class':'clear'}).inject(viewdiv, 'after');
			
			var playlist = new Element('div', {'id': 'play'+mediaId, 
									   'styles': {'position':'absolute', 'margin-top':'8px', 'margin-left':'-9px', 'cursor':'pointer'}, 
									   'events': {'click': function() { addtoplayList(mediaId, false, title, description, videoURL, thumbURL, duration, viewcount, created, votes); showDivSetClass('playlist','playercategories','playlistcontent'); }} // Just add to playlist and send media id
									   }).inject(imgcont, 'before');
			
			
			if(initScript==0) //If page already loaded
			{

				if(__checkCurrentVideo(mediaId)) { //check current playing video in flash, flash will return true or false
			
				previousNowplaying = 'play'+mediaId;

				var playimg = new Element('img', {'src': 'images/media_playing.png','width':'87px','height':'27px'}).inject(playlist);
							
				} else {
					
				 var playimg = new Element('img', {'src': 'images/media_addtoplaylist.png','width':'87px','height':'27px'}).inject(playlist);


				}
			}else{
				var playimg = new Element('img', {'src': 'images/media_addtoplaylist.png','width':'87px','height':'27px'}).inject(playlist);
				//$('play'+mediaId).addEvent('click', addplayEvent);
			}
			el.inject($('allmediacont'));
			
			if(pageStarted == 1) {
				//alert('here1');
		
				 // Play and send media id
				//	pageStarted = 2;
					
					
				if(qmedid != '') {
				
					//removeFromPlaylist(mediaId);
					getVidFromQuery ();
					pageStarted = 2;
				} else {
					
						addtoplayList(mediaId, true, title, description, videoURL, thumbURL, duration, viewcount, created, votes);
				//	alert('here2');
					showDivSetClass('playing','playercategories','playingcontent'); 
					pageStarted = 2;
					
				}
				
			}
		
		

			return count;
			
	
			
}


var ratingGet = function(imgdiv,mediaid)
{
	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/RatingGet.php',
			onRequest: function() {
				//displayloader
				     //  new Element('img', {'src': 'images/ajax-loader.gif'}).inject(imgdiv);
			},
			onComplete: function(jsonObj) {
	
				if(jsonObj['result'] == 'failed'){
					alert('failed');

				} else {
						imgdiv.empty();
						new Element('img', {'src': 'images/star'+Math.round(jsonObj.RatingGetResult.Item.AverageVotes)+'.jpg'}).inject(imgdiv);
				}
				
				
			}
		}).send('mediaId='+mediaid);
}







removeFromPlaylist = function(mediaID){		

	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/PlaylistDeleteMedia.php',
			onRequest: function() {
				//displayloader
			},
			onComplete: function(jsonObj) {
	
				if(jsonObj['result'] == 'failed'){
					alert('failed');

				} else {
					//alert('here');
				//	alert(jsonObj.PlayListCreateResult.Item.Id);
					//alert(playlistId);
					//playlistId = jsonObj.PlayListCreateResult.Item.Id;
					//alert(playlistId);
					$(mediaID).dispose();
				}
				
				
			}
		}).send('playListId='+playlistId+'&mediaId='+mediaID);
	
		
}


var addVideoToUl = function(ulid, mediaid, playing, medtitle, meddescription, medurl, medimage, medialength, views, mediadate, votes) {


	var li = new Element('li', {'id': mediaid, 'class':'playlistli'});
	var imgdiv = new Element('div', {'id': mediaid+mediaid, 'class':'imgplay',
									 'styles': {'cursor':'pointer'},
							         'events':{'click':function(){__playVideo(mediaid);}}}).inject(li);
	var img = new Element('img', {'src': medimage,'width':'110px','height':'60px',
						  'styles': {'width':'110px', 'height':'60px'}
						  }).inject(imgdiv);

	var textcontdiv = new Element('div', {'class':'textplaycont'}).inject(li);
	var title = new Element('h2', {'html': medtitle.substring(0,25)+'...', 'class':'videotitle'}).inject(textcontdiv);
	var para = new Element('p', {'html': meddescription.substring(0,25)+'...', 'class':'videodesc'}).inject(title, 'after');
	var remove = new Element('div', {
							 'styles': {'padding-top':'10px', 'padding-left':'10px'},
							 'events': {'click': function() { removeFromPlaylist(mediaid);__removeVideo(mediaid); }}}).inject(para, 'after');
	var a = new Element('a', {'html':'Remove', 'class':'removelink'}).inject(remove);
	li.inject($('listofplaylist'));
	
	if(playing == true) {
	//	changeStatus(mediaid+mediaid, mediaid, medtitle, meddescription, medurl, medimage, medialength, views, mediadate, votes);
	}
}


function two(x) {return ((x>9)?"":"0")+x}
function three(x) {return ((x>99)?"":"0")+((x>9)?"":"0")+x}

function time(ms) {
	var sec = Math.floor(ms/1000)
	ms = ms % 1000
	t = three(ms)
	
	var min = Math.floor(sec/60)
	sec = sec % 60
	t = two(sec) 
	
	var hr = Math.floor(min/60)
	min = min % 60
	t = two(min) + ":" + t
	
	var day = Math.floor(hr/60)
	hr = hr % 60
	t = two(hr) + ":" + t
//	t = day + ":" + t
	
	return t
}

function makehtml(text) {
var textneu = text.replace(/&/,"&amp;");
textneu = textneu.replace(/</,"&lt;");
textneu = textneu.replace(/>/,"&gt;");
textneu = textneu.replace(/\r\n/,"<br>");
textneu = textneu.replace(/\n/,"<br>");
textneu = textneu.replace(/\r/,"<br>");
return(textneu);
}	

function updateNowPlaying(medtitle, meddescription, medurl, medimage, medialength, views, mediadate, votes,mediaid) {
	
	var wrappeddiv = $('playingcontent');
	var myDate = new Date(mediadate.substring(0,10).replace(/-/gi,"/"));
	var m_names = new Array("January", "February", "March", 
	"April", "May", "June", "July", "August", "September", 
	"October", "November", "December");

	var curr_date = myDate.getDate();
	var curr_month = myDate.getMonth();
	var curr_year = myDate.getFullYear();

	var newdate = curr_date + " " + m_names[curr_month] + " " + curr_year;
	
	wrappeddiv.empty();
	
	var h4 = new Element('h4', {'html': medtitle+' <span class="timer">('+time(medialength)+')</span>'}).inject(wrappeddiv);
	var dateofdiv = new Element('div', {'html': newdate, 'class':'dateofvid'}).inject(h4, 'after');
	
	var ratediv = new Element('div', {'styles': {'padding-bottom':'7px' }}).inject(dateofdiv, 'after');
	var imgdiv = new Element('div', {'styles': {'float':'left', 'margin-right':'5px'}}).inject(ratediv);
	
	
	//ADD RATING SCRIPT
	doRating(0, true, {
        targetObject: imgdiv,
		background: '#fff', // vote cell background
        colourBase: '#91c532', // start colour (left side)
        colourTarget: '#91c532', // end colour (right side)
        maxStars: 5, // number of stars 
        starWidth: 15, // box with
        starHeight: 17, // box height
        starSpacing: 0, // space between stars
        imageURL: "/images/star.gif", // url to box background image
        tipPadding: 8, // padding around the vote text
        tipSize: "12px", // size of text in tip
        tipShown: false, // toggle tips
        clickEvent: function(ratingOptions) { // save the vote
            new Request({
                url: "ajax/RatingSubmit.php",
                method: "get",
                onComplete: function(jsonObj) {
                    //alert("isSuccessful: "+jsonObj.RatingSubmitResult.Item.IsSuccess);
                }
            }).send("sessionId="+sessionId+"&mediaId="+mediaid+"&vote="+ratingOptions.newRating);
        }
    });	
	
	
	//var stars = new Element('img', {'src': 'images/star_holder.jpg'}).inject(imgdiv);
	
	var viewdiv = new Element('div', {'styles': {'float':'left', 'padding':'4px'}}).inject(imgdiv, 'after');
	var spanview = new Element('span', {'html': views+' views', 'class':'viewcount'}).inject(viewdiv);
	var cleardiv2 = new Element('div', {'class':'clear'}).inject(viewdiv, 'after');
//	alert(meddescription);
	var paragraph = new Element('p', {'id': 'nowPlayingdesc', 'html': meddescription}).inject(ratediv, 'after');
	var social = new Element('p', {'html': '<br><a id="face1" target="_blank" href="" class="linkIcon facebook">&nbsp;&nbsp;</a> <a id="twit1" target="_blank" href="" class="linkIcon twitter">&nbsp;&nbsp;</a> <a id="yamm1" target="_blank" href="" class="linkIcon yammer">&nbsp;&nbsp;</a><a id="linker1" target="_blank" href="" class="linkIcon linker1">&nbsp;&nbsp;</a>' }).inject(paragraph, 'after');
	var input = new Element('input', {'id': 'linkin1', 'size': '50', 'styles' : {'display':'none'}}).inject(social, 'after');
	//getSmallUrl(escape('http://deloittetv.deloitte.com.au/index.html?mediaId='+mediaid+'&medtitle='+medtitle+'&meddescription='+escape(meddescription)+'&medurl='+medurl+'&medimage='+medimage+'&duration='+medialength+'&viewcount='+views+'&created='+mediadate+'&votes='+votes));
	getSmallUrl('http://deloittetv.deloitte.com.au/?mediaId='+mediaid);
	
	
	initScript = 0;
	
}


var loadCatdescription= function(CategoryGetResult, rss) {
	$('rssid').setStyle('display', 'inline');
	$('cattitle').innerHTML = CategoryGetResult.Item.Title;
	$('rssid').setProperty('href', rss);
	$('catdescription').innerHTML = CategoryGetResult.Item.Description;
}


function resetSortClass() {
	$('sortlinks').getElements('a').set('class', 'sortinglinks');
}

function clearPrevious() {
	if(previousNowplaying != '') {
//	alert(previousNowplaying);
//	alert($chk($(previousNowplaying)));
	if($chk($(previousNowplaying))) {
		 $(previousNowplaying).empty();
		 var prevbottomplayingimg = new Element('img', {'src': 'images/media_addtoplaylist.png','width':'87px','height':'27px'}).inject(previousNowplaying);
	}
	}
	
}

// Change image from playlist to playing for items in the playlist
changeStatus = function(mediaidlong, mediaid, medtitle, meddescription, medurl, medimage, medialength, views, mediadate, votes) {
	// alert('changing');
	 if($('statusupdate') != null) { $('statusupdate').dispose(); }
	 var liofmedia = $(mediaidlong);
	 var playing = new Element('div', {'id':'statusupdate', 'styles': {'position':'static', 'margin-top':'-55px', 'margin-left':'-10px'}}).inject(liofmedia);
	 var playingimg = new Element('img', {'src': 'images/media_playing.png','width':'87px','height':'27px'}).inject(playing);
	 

	if(qmedid == '' || qpageLoad == 1) {
		
	 clearPrevious();
	 var bottomplaylistdiv = $('play'+mediaid);
	 bottomplaylistdiv.empty();
	// bottomplaylistdiv.removeEvents('click');
	 var bottomplayingimg = new Element('img', {'src': 'images/media_playing.png','width':'87px','height':'27px'}).inject(bottomplaylistdiv);

	previousNowplaying = 'play'+mediaid;
	}
	updateNowPlaying(medtitle, meddescription,  medurl, medimage, medialength, views, mediadate, votes,mediaid);
 	qpageLoad = 1;
}



function showDivSetClass(id, parent, divtoshow) {
	//Reset all classes of all a tags in the div playercategories
	$(parent).getElements('a').set('class', 'categories');
	// Set Selected Class
	$(id).set('class', 'categoriesclicked');
	
	if(divtoshow != ''){
		
		$('hiddendivs').getElements('div.hidden').set({'styles': {'display':'none'}});
		$(divtoshow).set({'styles': {'display':'block'}});
		
	}

}



function createPlaylist(mediaid, playing){		



	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/PlaylistCreate.php',
			onRequest: function() {
				//displayloader
			},
			onComplete: function(jsonObj) {
	
				if(jsonObj['result'] == 'failed'){
					alert('failed');

				} else {
					//alert('here');
				//	alert(jsonObj.PlayListCreateResult.Item.Id);
					//alert(playlistId);
					playlistId = jsonObj.PlayListCreateResult.Item.Id;
					playlistAddMedia(playlistId, mediaid, playing);

					//alert(playlistId);
				}
				
				
			}
		}).send();
	
		
}

function createSession(){		



	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/SessionCreate.php',
			onRequest: function() {
				//displayloader
			},
			onComplete: function(jsonObj) {
	
				if(jsonObj['result'] == 'failed'){
					alert('failed');

				} else {
				
					sessionId = jsonObj.SessionCreateResult.Item.Id;
				
				}
				
				
			}
		}).send();
	
		
}

function playlistAddMedia(listID, mediaID, play){		

	
	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/PlaylistAddMedia.php',
			onRequest: function() {
				//displayloader
			},
			onComplete: function(jsonObj) {
	
				if(jsonObj['result'] == 'failed'){
					alert('failed');

				} else {
					//alert('here');
				//	alert(jsonObj.PlayListCreateResult.Item.Id);
					//alert(playlistId);
					//playlistId = jsonObj.PlayListCreateResult.Item.Id;
					//alert(playlistId);
				}
				
				
			}
		}).send('playListId='+listID+'&mediaId='+mediaID);
	
		
}


clearPlaylist = function(type){		

	var wrappeddiv = $('listofplaylist');
	var wrappedplayingdiv = $('playingcontent');

	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/PlaylistClear.php',
			onRequest: function() {
				//displayloader
			},
			onComplete: function(jsonObj) {
	
				if(jsonObj['result'] == 'failed'){
					alert('failed');

				} else {
					
					
					wrappeddiv.empty();
					wrappedplayingdiv.empty();
					clearPrevious();
				
					
					if(type=='javascript')
					{
						//clearPrevious();
						__createPlaylist();
						__clearPlaylist();
					}
				}
				
				
			}
		}).send('playListId='+playlistId);
	
		
}


//simple validator
var isEmpty = new InputValidator('required', {
    errorMsg: 'This field is required.',
    test: function(field){
        return ((field.get('value') == null) || (field.get('value').length == 0)  || (field.get('value') == 'Search Deloitte TV'));
    }
});


var textforsearch = $('search1');
textforsearch.addEvents({
  'focus': function(){ if(isEmpty.test($("search1")))  { textforsearch.set('value', ''); } $('search_error').empty();},
  
  'blur': function(){ if(isEmpty.test($("search1")))  { textforsearch.set('value', 'Search Deloitte TV'); }}
});
//isEmpty.test($("firstName")); //true if empty
//isEmpty.getError($("firstName")) //returns "This field is required."

var searchMedia = function() {

	if(isEmpty.test($("search1"))) {		

		var error = isEmpty.getError($("firstName")) //returns "This field is required."
		$('search_error').set('text', error);
	} else {
	
		var param = $('search1').get('value');
		//var searchPageInd = 1;
		
		$('nextbutton').removeEvents('click');
		$('previousbutton').removeEvents('click');
		
		
		$('nextbutton').addEvent('click', function(){getSearchMedia(param,tempsearchPageInd+1)});
		$('previousbutton').addEvent('click', function(){getSearchMedia(param,tempsearchPageInd-1);});
		
		getSearchMedia(param, 0);
	}
	
}


var prepareSearch = function (param, totalrecords) {

	
	$('cattitle').set('text', 'Searching Deloitte TV'); // populate heading for search
	$('rssid').setStyle('display', 'none');
	$('catdescription').set('html', 'Search results based on keyword: "'+param+'" has returned '+totalrecords+' results. <br><br> Click <a id="goback" class="sortinglinks">here</a> to see all videos.'); // populate paragraph

//	var returntext = new Element('div', {'html': 'click <a id="goback">here</a> to see all videos.', 'id':'returnsearchdiv'}).inject($('catdescription'), 'after');
	
	$('goback').addEvent('click', function(){categoryGet(tempId, tempRss);showDivSetClass(tempSelectClass,'maincategories','');
});
	

	$('maincategories').getElements('a').set('class', 'categories'); // set all category classes to grey
	$('sortlinks').set('styles', {'display': 'none' }); // disable sorting on search

	
}


var getSearchMedia = function(param, searchPageInd){		

	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/MediaSearch.php',
			onRequest: function() {
				
				$('allmediacont').fancyHide();
				$('allmediacont_loader').fancyShow();
				buildMainPreloader($('allmediacont_loader'));
				
			},
			onComplete: function(jsonObj) {

	
				if(jsonObj['result'] == 'failed'){
					
					alert('failed');
	
				} else {
										
					var totalpages = jsonObj.MediaSearchResult.ItemInfo.PageCount;
					var currentpage = jsonObj.MediaSearchResult.ItemInfo.PageCurrent;
					var totalrecords = jsonObj.MediaSearchResult.ItemInfo.TotalRows;
					if(totalrecords == -1) {totalrecords = 0; }
					if(totalpages == 0) { currentpage = 0; }
					
					prepareSearch(param, totalrecords);
					updatePage(totalpages, currentpage);

					if(currentpage == 1 || currentpage == 0) { $('prev').setStyle('display', 'none'); } else { $('prev').setStyle('display', 'inline'); }
					if(currentpage == totalpages) { $('next').setStyle('display', 'none'); } else { $('next').setStyle('display', 'inline'); }
					
					if(totalrecords != 0) {
					loadMediaForCat(jsonObj.MediaSearchResult.Item.MediaBase);
					} else {
					$('allmediacont_loader').fancyHide();
					}

				  
 				}
				
				
			}
		}).send('searchWord='+param+'&pageIndex='+searchPageInd);
	//tempInd = pageindex;
	tempsearchPageInd = searchPageInd;
//	$(tempSort).set('class', 'sortinglinksclicked');*/

}



var getSmallUrl = function(url){		

	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/bitlysoap.php',
			onRequest: function() {
								
			},
			onComplete: function(jsonObj) {

	
				if(jsonObj['result'] == 'failed'){
					
					alert('failed');
	
				} else {
						
					
					//var smallUrl = jsonObj['result'];
					//alert(url);
					var smallUrl = url;
					
					$('face1').setProperty('href', 'http://www.facebook.com/share.php?u='+smallUrl);
					$('twit1').setProperty('href', 'http://www.twitter.com/home?status=Deloitte+TV+-+'+smallUrl);
					$('yamm1').setProperty('href', 'https://www.yammer.com/home/bookmarklet?t=Deloitte TV&u='+smallUrl);
					
			
			$('linker1').addEvent('click', function (event) {
				event.stop();
				if($('linkin1').getStyle('display') == 'none') {
					$('linkin1').setStyle('display', 'inline');
				} else {
					$('linkin1').setStyle('display', 'none');
				}
			});
	
					
					$('linkin1').value = smallUrl;
					
					//alert(smallUrl);
 				}
				
				
			}
		}).send('url='+url);

}


/*function mediaGet(mediaID){		

	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/MediaGet.php',
			onRequest: function() {
				//displayloader
			},
			onComplete: function(jsonObj) {
	
				if(jsonObj['result'] == 'failed'){
					alert('failed');

				} else {
					//alert('here');
				//	alert(jsonObj.PlayListCreateResult.Item.Id);
					//alert(playlistId);
					var idofmedia = jsonObj.MediaGetResult.Item.MediaId;
					var playlistId = jsonObj.MediaGetResult.Item.MediaTitle;
					var playlistId = jsonObj.MediaGetResult.Item.MediaDescription;
					var playlistId = jsonObj.MediaGetResult.Item.MediaUrl;

					//alert(playlistId);
					//return jsonObj.MediaGetResult.Item.MediaTitle
					addVideoToDiv(idofmedia, playing);
				}
				
				
			}
		}).send('mediaId='+mediaID);
	
		
}*/



function addtoplayList(mediaid, playing, medtitle, meddescription, medurl, medimage, medialength, views, mediadate, votes) {


		goTOP();
		
		if(playlistId == '') {
			createPlaylist(mediaid, playing);
		} else {
			playlistAddMedia(playlistId, mediaid, playing);	
		}
		
		
		// add to playlist div
		addVideoToUl($('listofplaylist'), mediaid, playing, medtitle, meddescription, medurl, medimage,  medialength, views, mediadate, votes);
	//	alert(medurl);
		//add video to flash playlist
		addVideoToPlaylist(mediaid, playing, medtitle, meddescription, medurl, medimage, medialength, views, mediadate, votes);
			//alert(medurl);
		
		
}



var categoryGetMedia = function(catid, pageindex, sortby){		

	resetSortClass();
	catid=(catid=='')?tempId:catid;
	pageindex=(pageindex=='')?tempInd:pageindex;

	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/MediaListPagination.php',
			onRequest: function() {
				
				$('allmediacont').fancyHide();
				$('allmediacont_loader').fancyShow();
				buildMainPreloader($('allmediacont_loader'));
				
			},
			onComplete: function(jsonObj) {

	
				if(jsonObj['result'] == 'failed'){
					
					alert('failed');
	
				} else {
					//alert('loading');
					loadMediaForCat(jsonObj.MediaListPaginationResult.Item.MediaBase);
					//alert('loading');
					var totalpages = jsonObj.MediaListPaginationResult.ItemInfo.PageCount;
					var currentpage = jsonObj.MediaListPaginationResult.ItemInfo.PageCurrent;
					updatePage(totalpages, currentpage);
					
					if(currentpage == 1) { $('prev').setStyle('display', 'none'); } else { $('prev').setStyle('display', 'inline'); }
					if(currentpage == totalpages) { $('next').setStyle('display', 'none'); } else { $('next').setStyle('display', 'inline'); }
				  
 				}
				
				
			}
		}).send('catID='+catid+'&pageInd='+pageindex+'&sortBy='+sortby);
	tempInd = pageindex;
	tempSort = sortby;
	$(tempSort).set('class', 'sortinglinksclicked');

}

var resetNormalLinks = function () {

		$('nextbutton').removeEvents('click');
		$('previousbutton').removeEvents('click');


		$('nextbutton').addEvent('click', function(){categoryGetMedia('',tempInd+1,tempSort)});
		$('previousbutton').addEvent('click', function(){categoryGetMedia('',tempInd-1,tempSort);});

		$('sortlinks').set('styles', {'display': 'inline' }); // put back the sort links that the search took out

						
}


var categoryGet = function(catid, rss){		
	
	var request =  new Request.JSON({
			method: 'get',
			url: 'ajax/CategoryGet.php',
			onRequest: function() {
				//displayloader

			},
			onComplete: function(jsonObj) {
	
				if(jsonObj['result'] == 'failed'){
					alert('failed');

				} else {
					
						resetNormalLinks(); // to undo what the search has done, show links and fix next and previous.
						tempSort=(catid!=tempId)?defSort:tempSort;
						tempInd=1;						
						categoryGetMedia(catid,tempInd,tempSort);
						loadCatdescription(jsonObj.CategoryGetResult, rss);
						tempId = catid;
						tempRss = rss;

				}
				
				
			}
		}).send('catID='+catid);
	
		
}


var buildMainPreloader = function(div)
{
			div.empty();
			var imgcont = new Element('div', {'styles': {'width':'630px','height':'430px'}}).inject(div);			
			var loader = new Element('img', {'src': 'images/ajax-loader.gif','styles': {'margin-top':'180px','margin-left':'290px'}}).inject(imgcont);	
			
}


var goTOP = function() {
//scroll down to the specific spot
	var scroll = new Fx.Scroll(window, { wait: false, duration: 2500, transition: Fx.Transitions.Quad.easeInOut });
	scroll.toElement('top');
}



	//time to implement basic show / hide
	Element.implement({
		//implement show
		show: function() {
			this.setStyle('display','');
		},
		//implement hide
		hide: function() {
			this.setStyle('display','none');
		}
	});

	//time to implement fancy show / hide
	Element.implement({
		//implement show
		fancyShow: function() {
			this.fade('in');
		},
		//implement hide
		fancyHide: function() {
			this.fade('out');
		}
	});




categoryGet(tempId, tempRss);
showDivSetClass(tempSelectClass,'maincategories','');
showDivSetClass('playlist','playercategories','playlistcontent');
createSession();




/*************************
 AquaPlayer AS3 FlashComs 
**************************/

// inject AquaPlayer AS3 into page
var AquaPlayer = new Swiff('AquaPlayer AS3/AquaPlayer.swf', {
					width:  587, 
					height: 362, 
					container: $('flashplayer'),
					params: 
					{
						  quality: "high",
						  align: "middle",
						  scale: "exactfit",
						  allowFullScreen: "true",
						  bgcolor: "#000000",
						  allowscriptaccess: "always"
					},
					 events: {
        onLoad: function() {
            alert("Flash is loaded!")
        }
    }

					
				}).toElement();
			
			
var addVideoToPlaylist = function(id, playing, medtitle, meddescription, medurl, medimage,  medialength, views, mediadate, votes)
{
			Swiff.remote(AquaPlayer, 'addVideoToPlaylist', id, playing, medtitle, meddescription, medurl, medimage, medialength, views, mediadate, votes);
			//alert( playing+' , '+ medtitle+' , '+ meddescription+' , '+ medurl+' , '+ medimage+' , '+ medialength+' , '+ views+' , '+ mediadate+' , '+ votes);
}

var __clearPlaylist = function()
{
			Swiff.remote(AquaPlayer, '__clearPlaylist');			
}

var __playVideo = function(mediaid)
{
			Swiff.remote(AquaPlayer, '__playVideo', mediaid);

}

var __removeVideo = function(mediaid)
{
	  Swiff.remote(AquaPlayer, '__removeVideo', mediaid);
}

var __checkCurrentVideo = function(mediaid)
{
	
	  var val =  Swiff.remote(AquaPlayer, '__checkCurrentVideo', mediaid);
	//  alert(val);
	  return val;
	//return 0;
}

var __createPlaylist = function()
{
	Swiff.remote(AquaPlayer, 'createPlaylist');
}

/**************************/

});
