/**************************************/
/********** MTVM UTILS *****************/
/*
	Dependencies: 
	 -MTVM.util.checkFlashVersion requires AC_OETags.js
*/
/**************************************/

//Additional methods for String
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


MTVM.util.getServerPlatform = function()
{
	if(document.location.hostname.indexOf("mtvi.com")>-1)
	{
		if(document.location.hostname.indexOf("-l.mtvi.com")>-1)
		{
			return "l"; //local
		}

		if(document.location.hostname.indexOf("-d.mtvi.com")>-1)
		{
			return "d";
		}
		else if(document.location.hostname.indexOf("-q.mtvi.com")>-1)
		{
			return "q";
		}
	}
	else
	{return "live";}
}


//credits: www.hunlock.com
//check if css rule exists
MTVM.util.getCSSRule = function(ruleName, deleteFlag)		// Return requested style obejct
{
    ruleName=ruleName.toLowerCase();                       // Convert test string to lower case.
   if (document.styleSheets) {                            // If browser can play with stylesheets
      for (var i=0; i<document.styleSheets.length; i++) { // For each stylesheet
         var styleSheet=document.styleSheets[i];          // Get the current Stylesheet
         var ii=0;                                        // Initialize subCounter.
         var cssRule=false;                               // Initialize cssRule. 
         do {                                             // For each rule in stylesheet
            if (styleSheet.cssRules) {                    // Browser uses cssRules?
               cssRule = styleSheet.cssRules[ii];         // Yes --Mozilla Style
            } else {                                      // Browser usses rules?
               cssRule = styleSheet.rules[ii];            // Yes IE style. 
            }                                             // End IE check.
            if (cssRule)  {                               // If we found a rule...
               if (cssRule.selectorText.toLowerCase()==ruleName) { //  match ruleName?
                  if (deleteFlag=='delete') {             // Yes.  Are we deleteing?
                     if (styleSheet.cssRules) {           // Yes, deleting...
                        styleSheet.deleteRule(ii);        // Delete rule, Moz Style
                     } else {                             // Still deleting.
                        styleSheet.removeRule(ii);        // Delete rule IE style.
                     }                                    // End IE check.
                     return true;                         // return true, class deleted.
                  } else {                                // found and not deleting.
                     return cssRule;                      // return the style object.
                  }                                       // End delete Check
               }                                          // End found rule name
            }                                             // end found cssRule
            ii++;                                         // Increment sub-counter
         } while (cssRule)                                // end While loop
      }                                                   // end For loop
   }                                                      // end styleSheet ability check
   return false;                                          // we found NOTHING!
}                                                                         // end getCSSRule 


MTVM.util.parseUrlParamsToJSON = function()
{
	var searchString = document.location.search;
	var jsonObj		 = null;
	
	if(searchString.length>1)
	{
		searchString = searchString.substr(1, searchString.length);	//remove leading ?
		searchString = searchString.replace(/=/g, ":'");
		searchString = searchString.replace(/&/g, "',");
		searchString = searchString.replace(/&/g, "',");
		searchString = "{"+searchString+"'}";
		eval ("jsonObj="+searchString);
	}
	return jsonObj;
}

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

MTVM.util.getCookie = function(c_name)
{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{ 
		c_start=c_start + c_name.length+1; 
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		} 
	  }
	return "";
}


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



/***************** ELLIPSIS / TRUNCATE TEXT *******************/		
	/***USAGE: "elementID" is the element you want to operate on***/
	/*** if no elementId available, you can pass the html element itself as the context of "this"***/
	/***"length" is the length you want the element to truncate at*/
	/**************************************************************/
MTVM.util.truncateText = function(elementId, truncateLength, htmlElement)
{
		var p = null;
		
		if(elementId)
		{p = document.getElementById(elementId);}
		else
		{p = htmlElement;}
		
		if (p) {			
		  var trunc = p.innerHTML;
		  if (trunc.length> truncateLength) {
		  
			/* Truncate the content of the element, then go back to the end of the
			   previous word to ensure that we don't truncate in the middle of
			   a word */
			trunc = trunc.substring(0, truncateLength);
			trunc = trunc.replace(/\w+$/, '');

			/* Add an ellipses to the end and make it a link that expands
			   the paragraph back to its original size */
			trunc += '<a href="#" ' +
			  'onclick="this.parentNode.innerHTML=' +
			  'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
			  '...<\/a>';			
			p.innerHTML = trunc;
		  }
		}
}
	
	
/***************** ELLIPSIS / TRUNCATE STRING *******************/		
/**************************************************************/
MTVM.util.truncateString = function(textString, truncateLength, truncateMode )
{
	if(truncateMode == null || truncateMode == "")
	{
		truncateMode = "hard";
	}
	
	switch(truncateMode)
	{
		default:
	  		if	(textString.length> truncateLength)
	  		{	  
				textString = textString.substring(0, truncateLength);			
				/* Add an ellipses to the end*/
				textString += '...';			
			}
			break;
	}
	  

	return textString;		
}

MTVM.util.flattenString = function (str) {
	var re = /[^0-9A-Za-z\s]/g;
	var flattenedStr = str.replace(re, "");
	var re2 = /\s+/g;
	flattenedStr = flattenedStr.replace(re2, "_");
	flattenedStr = MTVM.util.truncateString(flattenedStr, 10);
	return flattenedStr;
}


MTVM.util.escapeQuotes = function(string)
{
	
	string = string.replace(/\'/g, "&#39;");
	string = string.replace(/\"/g, "&#34;");
	return string;
}

MTVM.util.Clipboard = {}

MTVM.util.Clipboard.copyEmbed = function()
{
	document.getElementById('videoEmbedInput').select();
	return document.getElementById('videoEmbedInput').value;
}

MTVM.util.Clipboard.copyUrl = function()
{
	document.getElementById('urlInput').select();
	return document.getElementById('urlInput').value;
}


MTVM.util.checkFlashVersion = function (requiredMajorVersion, requiredMinorVersion, requiredRevision)
{
	var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	
	if (hasRequestedVersion) {return true;}
	else{
		return false;
	}
}


MTVM.util.randomize	=	function(max) //randomize a number from 0 to max
{
	var random = 0;
	random = Math.floor(Math.random()*max);
	return(random);
}



/***************** ELLIPSIS / TRUNCATE WORD WITH CONSIDERATION of SPACE *************/		
/*** USAGE: "elementID" is the element you want to operate on           *************/
/*** if no elementId available, you can pass the html element itself    *************/
/*** as the context of "this""length" is the length you want the 		*************/
/*** element to truncate at.                                             *************/
/**
elementId:		id of the html element
htmlElement:	when there is no html element id avail, you can pass in "this" with the script call.
truncateLength:	the length where you want to truncate a word.
breakType:		dictates how the word will be broken up. 1 = space, 2 = <br>
*/
/************************************************************************************/

MTVM.util.truncateWord=  function(elementId, htmlElement, truncateLength, breakType){
	var theElement = null;
	
	if(elementId)
	{theElement = document.getElementById(elementId);}
	else
	{theElement = htmlElement;}
	
	if (theElement)
	{			
	  var entireText = theElement.innerHTML;
	}
}
	
/************** LISTEN ON KEYSTROKE *******************/
MTVM.util.keyListener= function (evnt, element)	
{	
	var keyCode ="";
	var processKey = 
	{
		enter:	function(element) //ENTER key
		{	
			MTVM.util.submitSearch(element.id);
		}
	}		
	
	if(!evnt){evnt = window.event;} //for IE
	
	if (evnt.keyCode) keyCode = evnt.keyCode;
	else if (evnt.which) keyCode = evnt.which;
	
	
	switch(keyCode)
	{
	
		case 13: processKey.enter(element);break; //enter key
	}
	
	
}



MTVM.util.submitSearch=	function(inputElementId)
{		

	var value =	null;
	var serverName = null;
	
	if((document.getElementById(inputElementId)).value!='' && (document.getElementById(inputElementId)).value !=null)
	{

		value = (document.getElementById(inputElementId)).value.replace(/^\s*|\s(?=\s)|\s*$/g, "").toLowerCase();
		(document.getElementById(inputElementId)).value = value;
		value = escape(value);
		
		document.location = MTVM.config.serverHostName+'/'+MTVM.lang.utils.route_search+'/?term='+value+'&filter=music_video&mw=0';
	}

}

MTVM.util.checkSearchBox=	function(inputElementId)
{	
	var value =	null;
	var pass = false;
	
	if((document.getElementById(inputElementId)).value!='' && (document.getElementById(inputElementId)).value !=null)
	{
		value = (document.getElementById(inputElementId)).value;
		if (value == "TYPE ARTIST OR SONG"){
			document.getElementById(inputElementId).focus();
		}
		else if (value != "TYPE ARTIST OR SONG"){
			pass = true;
		}
	}
	return pass;
},


MTVM.util.clearDefSearchValue=	function(obj){
	var value = obj.value;
	
	if(value.toUpperCase() == MTVM.lang.utils.searchInputText.toUpperCase() && (window._searchFieldClicked== false || window._searchFieldClicked == null))
	{
		obj.value = "";
		window._searchFieldClicked = true;
	}
}






MTVM.util.hideThumbnails=	function(obj)
{	
	var col = $J('.videoThumbWrap');
	var col2 = $J('.artistThumbWrap');

	$J('.listView').css("color","#534c42"); 
	$J('.thumbnailView').css("color","#f90464"); 		

	
	if(col!= null && col != "")
	{
		for(i=0; i<col.length; i++)
		{
			col[i].style.display = "none";			
			if(i%2 == 0)
			{			
				col[i].parentNode.style.background = "#fff url('/sitewide/img/misc/gradient42.gif') repeat-x";
			}
		}
		$J('.videoDetails-addButton').css("margin-top", "10px");
	}

	if(col2!= null && col2 != "")
	{				
		for(i=0; i<col2.length; i++)
		{
			col2[i].style.display = "none";			
			if(i%2 == 0)
			{			
				col2[i].parentNode.style.background = "#fff url('/sitewide/img/misc/gradient42.gif') repeat-x";
			}
		}	
	}

}

MTVM.util.toggleVideoGroup=  function(gName, _hideAll)
{
	var groups = $J('div.videoGroup');
	var group = $J('div#'+gName);
	var hideAll = true;
	if (_hideAll != null) hideAll = _hideAll;
	if (group != null){
		if (hideAll){
			for (var i=0; i<groups.length; i++){
				MTVM.util.hideVideoGroup(groups[i]);
			}
		}
		//if (group.css("display") == "block" || group.css("display") == "undefined")
		if (group.is(':visible'))
			MTVM.util.hideVideoGroup(group);
		else
			MTVM.util.showVideoGroup(group);
	}
}
	MTVM.util.showVideoGroup=  function(obj){
		//obj.style.display = "block";
		//$(obj).css("display","block"); 
		$J(obj).show();
	}
	
	MTVM.util.hideVideoGroup=  function(obj){
		//obj.style.display = "none";
		//$(obj).css("display","none"); 
		$J(obj).hide();
	}
	
	MTVM.util.showAllVideoGroups=  function(vgName){
		var groups = $J('div.videoGroup');
		if (vgName != null) groups = $J(vgName);
		for (var i=0; i<groups.length; i++){
			if ($J(groups[i]).attr('id')=="hd")
				MTVM.util.hideVideoGroup(groups[i]);
			else 
				MTVM.util.showVideoGroup(groups[i]);
		}
	}

MTVM.util.showThumbnails=	function(obj)
{
	var col = $J('.videoThumbWrap');
	var col2 = $J('.artistThumbWrap');
	
	
	$J('.listView').css("color","#f90464"); 
	$J('.thumbnailView').css("color","#534c42"); 		
	

	if(col!= null && col != "")
	{

		for(i=0; i<col.length; i++)
		{
			col[i].style.display = "block";	
			col[i].parentNode.style.background = "#fff";
		}
		$J('.videoDetails-addButton').css("margin-top", "85px");
	}


	
	if(col2!= null && col2 != "")
	{

		for(i=0; i<col2.length; i++)
		{
			col2[i].style.display = "block";	
			col2[i].parentNode.style.background = "#fff";
		}	
	}


}

MTVM.util.generateThumbOverlay= function(vidToMatch, VideoThumbOverlays){
	if (VideoThumbOverlays != null && vidToMatch != null){
		var linkText = "";
		var linkStyle = "";
		for (var i=0; i < VideoThumbOverlays.length; i++){
			var listOfIds = VideoThumbOverlays[i].ids;
			var opaFF = VideoThumbOverlays[i].opacity / 100;
			//console.log(opaFF);
			linkText = VideoThumbOverlays[i].text;
			linkStyle = "background-color:"+VideoThumbOverlays[i].color+";filter: alpha(opacity="+VideoThumbOverlays[i].opacity+"); opacity: "+ opaFF +";";
			var listOfIdsArray = listOfIds.split(",");
			for (var x=0; x < listOfIdsArray.length; x++){
				//console.log("curr ID:'" + $J.trim(listOfIdsArray[x]) + "'");
    			if ($J.trim(listOfIdsArray[x]) == vidToMatch){
	            	var franchiseOverlay = '<div class="franchiseVideo" style="'+ linkStyle +'">&nbsp;</div>';
	            	franchiseOverlay += '<div class="franchiseVideo" style="color:white">'+ linkText +'</div>';
	            	if ("overlayImage" in VideoThumbOverlays[i]){
	            		franchiseOverlay = '<div class="franchiseVideoImage" style=""><img src="'+ VideoThumbOverlays[i].overlayImage +'" border="0"></div>';
	            	}
	            	//document.getElementById("thumbOverlay"+vidToMatch).innerHTML = franchiseOverlay;
	            	$J('.thumbOverlay'+vidToMatch).html(franchiseOverlay);
	            	//document.write(franchiseOverlay);
        		}
    		}
    	}
	}
}

MTVM.util.popNewWindow = function(url, wName, misc)
{
	if(misc == null || misc == "")
	{
		misc = 'toolbar=1,status=1,width=800,height=436';
	}
	
	if(MTVM.windows == null || MTVM.windows == "")
	{
		MTVM.windows = new Array();
	}
	
	if(url !="")
	{
		var newWindow  = window.open(url, wName, misc);			
	}
}


MTVM.util.socialNetwork ={
	shareUrl: "",
	shortUrl: "",
	mesg:		"",
	embed:	""
};

MTVM.util.socialNetwork.shortenUrl = function()
{
	var options = options || {};
	
	options.url = "/sitewide/dataservices/shortenUrl/?showComments=off&longUrl="+MTVM.util.socialNetwork.shareUrl;
	
	var url = ('url' in options) ? options.url : '';
	var ajaxType = ('ajaxType' in options) ? options.ajaxType : 'GET';
	var data = ('data' in options) ? options.data : '';
	var dataType = ('dataType' in options) ? options.dataType : 'json';
	var timeout = ('timeout' in options) ? options.timeout : 20000;
	
	try{
		$J.ajax({
			url: url,
			type: ajaxType,
			data: data,
			dataType: dataType,
			timeout: timeout,
			error: function(){ errorHandler(); },
			success: function(json) { successHandler(json); }
		});
	}
	catch(e){
		MTVM.logger.log("MTVM.util.socialNetwork.shortenUrl ajax failed: "+e, 2);
		MTVM.util.socialNetwork.shortUrl = "FAILED";
		MTVM.EventsManager.broadcast('onShortUrlReady');
	}	
	
	errorHandler = function()
	{
		MTVM.logger.log("MTVM.util.socialNetwork.shortenUrl ajax failed: ", 2);
		MTVM.util.socialNetwork.shortUrl = "FAILED";
		MTVM.EventsManager.broadcast('onShortUrlReady');
	}
	
	successHandler = function(json)
	{	
		if(json.shortUrl && json.shortUrl != "")
		{
			MTVM.util.socialNetwork.shortUrl = json.shortUrl;	
		}else
		{
			MTVM.util.socialNetwork.shortUrl = "FAILED";
		}		
		MTVM.EventsManager.broadcast('onShortUrlReady');
	}
}


MTVM.util.twitter = {}

MTVM.util.twitter.shareIt = function()
{
	MTVM.util.popNewWindow('about:blank','share');
	MTVM.EventsManager.addListener('onShortUrlReady', MTVM.util.twitter.shortenAndPop);
	MTVM.util.socialNetwork.shortenUrl();
}

MTVM.util.twitter.shortenAndPop = function()
{	
	if(MTVM.util.socialNetwork.shortUrl!="" && MTVM.util.socialNetwork.shortUrl !="FAILED")
	{
		MTVM.util.twitter.fullUrl = "http://twitter.com/home?status="+MTVM.util.socialNetwork.mesg+" "+MTVM.util.socialNetwork.shortUrl;
	}
	else
	{
		MTVM.util.twitter.fullUrl = "http://twitter.com/home?status="+MTVM.util.socialNetwork.mesg+" "+MTVM.util.socialNetwork.shareUrl;
	}
	MTVM.util.popNewWindow(MTVM.util.twitter.fullUrl, "share");
}




MTVM.util.facebook = {}
MTVM.util.facebook.shareIt = function()
{					
	MTVM.util.popNewWindow("about:blank","share");
	MTVM.util.facebook.click(MTVM.util.socialNetwork.shareUrl, MTVM.util.socialNetwork.mesg);
}
MTVM.util.facebook.click = function(u, t)
{
	u = u?u:location.href;
	t = t?t:document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'share','toolbar=0,status=0,width=626,height=436');
}



MTVM.util.myspace ={}
MTVM.util.myspace.shareIt = function()
{	
	MTVM.util.popNewWindow("about:blank","share");
	MTVM.util.myspace.getThis(MTVM.util.socialNetwork.mesg, MTVM.util.socialNetwork.embed, MTVM.util.socialNetwork.shareUrl);
}
MTVM.util.myspace.getThis= function(T, C, U, L)
{
	L = L?L:U;
	var targetUrl = 'http://www.myspace.com/Modules/PostTo/Pages/?' + 't=' + encodeURIComponent(T)+ '&c=' + encodeURIComponent(C) + '&u=' + encodeURIComponent(U) + '&l=' + L;
	window.open(targetUrl, 'share','toolbar=0,status=0,width=626,height=436');
}


MTVM.util.sonico ={}
MTVM.util.sonico.shareIt = function()
{	
	MTVM.util.popNewWindow("about:blank","share");
	MTVM.util.sonico.share(MTVM.util.socialNetwork.shareUrl, MTVM.util.socialNetwork.mesg);
}
MTVM.util.sonico.share= function(loc, title)
{	
	window.open('http://www.sonico.com/share.php?title='+encodeURIComponent(title)+'&url='+encodeURIComponent(loc),'share','toolbar=0,status=0,width=626,height=436');
}

MTVM.util.convertStringToArray = function() //converts space seperated string into an array
{
}

MTVM.util.isHD = function(width, height) //returns if video is hd or not
{
	if(MTVM.player.largestRenditionHeight != null && MTVM.player.largestRenditionHeight != "")
	{
		if(MTVM.player.largestRenditionHeight >= 720 && screen.height>=768)
		{
			return true;
		}else{
			return false;
		}
	}
	else
	{
		if(height >= 720 && screen.height>=768)
		{
			return true;
		}else{
			return false;
		}
	}	
}



var _void = function()
{
return false;
}