/* vim: set expandtab tabstop=3 shiftwidth=3 softtabstop=3: */
// declare a global  XMLHTTP Request object
var XmlHttpObj,i,forwardId='';
 // Major version of Flash required
var requiredMajorVersion = 8;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Revision of Flash required
var requiredRevision = 0;
// the version of javascript supported
var jsVersion = 1.0;

var curvyCornersAppliedToProcessIndicator = false;

var actualRankings = new Array();//Stores ranks
        
// -----------------------------------------------------------------------------
// -->
<!-- // Detect Client Browser type
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isIE6  = (navigator.appVersion.indexOf("MSIE 6.0") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isMac = (navigator.appVersion.toLowerCase().indexOf("mac") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var isSafari = (navigator.userAgent.indexOf("Safari") != -1) ? true : false;
var isMozilla = (navigator.userAgent.indexOf("Mozilla") != -1 && !isSafari) ? true : false;
var winloadFuns = '';

/******************************************/
// Code for detecting browser, browser version and OS
// added by madan
// BrowserDetect.browser to get the browser name.
// BrowserDetect.version to get the browser version.
// BrowserDetect.OS to get the operating system name.


var BrowserDetect = {
    init: function ()
    {
        this.browser = this.searchString(this.dataBrowser) || "an unknown browser";
        this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data)
    {
        for (var i=0;i<data.length;i++)
        {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString)
            {
                if (dataString.indexOf(data[i].subString) != -1)
                {
                    return data[i].identity;
                }
            }
            else if (dataProp)
            {
                return data[i].identity;
            }
        }
    },
    searchVersion: function (dataString)
    {
        var index = dataString.indexOf(this.versionSearchString);
		var browserV = dataString.substring(index+ this.versionSearchString.length + 1).split(" ");
		 if(browserV)
			return browserV[0];	
        if (index == -1)
        {
            return;
        }  
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
    {
        string: navigator.userAgent,
        subString: "Chrome",
        identity: "Chrome"
    },
    {
        string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
    },
    {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari",
        versionSearch: "Version"
    },
    {
        prop: window.opera,
        identity: "Opera"
    },
    {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
    },
    {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
    },
    {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox"
    },
    {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
    },
    {
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
    },
    {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE"
    },
    {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
    },
    {
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
    }
    ],
    dataOS : [
    {
        string: navigator.platform,
        subString: "Win",
        identity: "Windows"
    },
    {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
    },
    {
        string: navigator.userAgent,
        subString: "iPhone",
        identity: "iPhone/iPod"
    },
    {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
    }
    ]

};
BrowserDetect.init();
//alert( BrowserDetect.browser );
//alert( BrowserDetect.version );
//alert( BrowserDetect.OS );
  
/********************************************/

if(isIE)
{
	window.attachEvent('onload', onWinLoadExecutor, true);
}
else
{
	window.addEventListener('load', onWinLoadExecutor, true);
}

function onWinLoadExecutor()
{
	eval(winloadFuns);
}

function targetBlank(url, title)
 {
    var targetblank = window.open(url, title, "top = 0, left = 0, resizable = yes, width = "+screen.width+", height="+screen.height+", titlebar=yes, menubar=yes, toolbar = yes, location = yes, scrollbars = yes");
                    targetblank.moveTo(0,0);
                    targetblank.resizeTo(screen.width,screen.height);
 }

function openPopup(url,
                   title,
                   width,
                   height,
                   scrollbars)
{
  
   var x = (640 - width) / 2;
   var y = (480 - height) / 2;
	 
   if (screen)
   {
      y = (screen.availHeight - height) / 2;
      x = (screen.availWidth - width) / 2;
   } // if

   if (screen.availWidth > 1800)
   {
      x = ((screen.availWidth / 2) - width) / 2;
   } // if

   params = 'width='    + width  + ',' +
            'height='   + height + ',' +
            'screenX='  + x      + ',' +
            'screenY='  + y      + ',' +
            'top='      + y      + ',' +
            'left='     + x      + ',' +
            'dependent=yes,'  +
            'directories=no,' +
            'location=no,'    +
            'menubar=no,'     +
            'status=no,'      +
            'toolbar=no';
	
   if (scrollbars)
   {
      params += ',scrollbars=yes';
   } // if
   else
   {
      params += ',scrollbars=no';
   } // else


    var newWin = window.open(url,title,params);

	//newWin = window.open(url);
   //return (newWin);
}


/**
 * Removes child nodes from an element.
 *
 * @param Element elem  Element to remove child nodes from.
 */
function removeChildren(elem)
{
   while (elem.childNodes.length)
   {
      elem.removeChild(elem.firstChild);
   }
}

function sendMailThroughClient(subject,body)
{          
    location.href = "mailto:?Subject=" + escape(subject) + "&Body=" + escape(body);     
}

/*
function sendMailThroughClient(to,cc,bcc,subject,body)
{
	var mailIds = to.split(",");
	if(mailIds[0])
	{
		var emails = Array();
		
		for(var i = 0;i<mailIds.length;i++)
		{
			emails[i] = trim(mailIds[i]);
		} 
	}
	location.href = "mailto:"+(emails.join(","))+"?Subject=" + escape(subject) + "&Body=" + escape(body);
	
}
*/

/**
 * Trims the given string from the both ends.
 *
 * @param inputString - String to be trimmed
 */
function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { 
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, 
retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function


/**
   Gets response from server as a result of the AJAX call made in the createMax3Elink() and fills the 
   textarea on forward max3 page with the Elink string.
*/
function showElinkToForward(max3title,artist)
{
	if(window.XmlHttpObj.readyState == 4)
	{
		if(window.XmlHttpObj.status == 200)
		{	
			$('msgDiv').style.display = 'none';		
			var responseText = window.XmlHttpObj.responseText;
			switch(responseText)
			{
				case 'ERR#1':	alert('Server could not identify the max3 to be forwarded.');
						break;
				case 'ERR#2':	alert('Server could not identify the sender.');
						break;
				case 'ERR#3':	alert('No recipient address found.');
						break;
				case 'ERR#4':	alert('Sorry, the max3 you are trying to forward has been inactivated.');
						break;
				case 'ERR#5':	alert('Sorry, the max3 you are trying to forward is not active.');
						break;
				case 'ERR#6':	alert('No valid recipient email address found in the Send To list.');
						break;
				case '':	alert('Invalid request to the server.');
						break;
				default:	
						str = responseText.replace('\n','');
						str = str.replace('\r','');
						str = trim(str);
						window.forwardId = trim(responseText);
						$('max3ELink').style.display = '';
						$('max3ELink').value = MOJAVI_BASE_URL+'/em.3/'+str;
						$('max3ELink').focus();
						break;
			}
		}
		else
		{
			alert("problem retrieving Elink from the server, status code: "  + window.XmlHttpObj.status);
		}
	}
}


function getElementHeight(elem){
	var obj = $(elem);
	if(!obj)
		return 0;

	return obj.offsetHeight;
}

function getElementWidth(elem){
	var obj = $(elem);
	if(!obj)
		return 0;

	return obj.offsetWidth;
}

function getElementTop(elem){
	var obj = $(elem);
	if(!obj)
		return 0;

	if(isIE){
		//return obj.offsetParent.offsetTop + obj.offsetTop;
		//This is commented for IE7 twik
		return obj.offsetTop;
	}
	else{
		return obj.offsetTop;
	}
}

function getElementLeft(elem){
	var obj = $(elem);
	if(!obj)
		return 0;

	if(isIE){
		return obj.offsetParent.offsetLeft + obj.offsetLeft;
	}
	else{
		return obj.offsetLeft;
	}
}


/**
 * Calls a script on the server and gets the newly created E-link ID and fills the proper E-link string in
 * text area shown on the forward max3 page.
 *
 */
function createMax3Elink(max3uuid,max3title,artist,userid,forwardLink)
{
	//Get the email addresses from the SendTo list.
	var emailIds = trim($('sendTo').value);
	
	if(emailIds=='')
	{
		alert("Please specify the recipient's address/es.");
		return false;
	}
	
	CreateXmlHttpObj();
	if(!window.XmlHttpObj)
		return false;

	//var messageDiv = document.createElement('div');
	$('msgDiv').innerHTML = '<b>Generating E-link....Please Wait....</b>';
	$('msgDiv').style.display = '';
	centerMsgDiv();
	
	$('max3ELink').value = '';
	//Lets do some give n take. Give mail IDs to the server and get back the E-link ID in return.

	window.XmlHttpObj.onreadystatechange = function()
		{ 
	
						if(window.XmlHttpObj.readyState == 4)
						{
							if(window.XmlHttpObj.status == 200)
							{	
								$('msgDiv').style.display = 'none';		
								var responseText = window.XmlHttpObj.responseText;
								switch(responseText)
								{
									case 'ERR#1':	alert('Server could not identify the max3 to be forwarded.');
											break;
									case 'ERR#2':	alert('Server could not identify the sender.');
											break;
									case 'ERR#3':	alert('No recipient address found.');
											break;
									case 'ERR#4':	alert('Sorry, the max3 you are trying to forward has been inactivated.');
											break;
									case 'ERR#5':	alert('Sorry, the max3 you are trying to forward is not active.');
											break;
									case 'ERR#6':	alert('No valid recipient email address found in the Send To list.');
											break;
									case '':	alert('Invalid request to the server.');
											break;
									default:	
											str = responseText.replace('\n','');
											str = str.replace('\r','');
											str = trim(str);
											window.forwardId = str;
											$('max3ELink').style.display = '';
											$('max3ELink').value = MOJAVI_BASE_URL+'/em.3/'+str;
											$('max3ELink').focus();
											break;
								}
							}
							else
							{
								alert("problem retrieving Elink from the server, status code: "  + window.XmlHttpObj.status);
							}
						}
		};
	var requestUrl = "/m.3/module/Max3/action/getElinkId/";
	var params = "max3uuid="+escape(max3uuid)+"&sender="+userid+"&recipients="+escape(emailIds)+"&forwardLink="+escape(forwardLink)+"&defaultForwardId="+escape(window.forwardId);
	window.XmlHttpObj.open("POST", requestUrl,  true);
	window.XmlHttpObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	window.XmlHttpObj.setRequestHeader("Content-length", params.length);
	window.XmlHttpObj.setRequestHeader("Connection", "close");
	window.XmlHttpObj.send(params);	
	
}


function openForwardMail(subject,body)
{
	//Get the email addresses from the SendTo list.
    var emailIds = trim($('sendTo').value);
    
    if(emailIds=='')
    {
        alert("Please specify the recipient's address/es.");
        return false;
    }
    
	var to = $('sendTo').value;
	var subject = subject;
	var cc = '';
	var bcc = '';
	var body = '';
	sendMailThroughClient(to,cc,bcc,subject,body)
}

function centerDiv(id)
{  


  
    if(!$(id))
        return false;              
        
    var pageScrollStats = getScrollStats();
    var windowWidth = GetWindowWidth();
    var windowHeight = GetWindowHeight();
   
    var divWidth = $(id).clientWidth;
    var divHeight = $(id).clientHeight;            
   
    divWidth = divWidth ? divWidth : (windowWidth/2) ;
    divHeight = divHeight ? divHeight : (windowHeight/2); 
             
           
    //To center element according to window scroll.
	$(id).style.top = ''+Math.round(pageScrollStats[1]+((windowHeight/2)-(divHeight/2)))+'px'; 
    $(id).style.left = ''+Math.round(pageScrollStats[0]+((windowWidth/2)-(divWidth/2)))+'px';          
    
    
    
    //To center element to a fixed position irrespective of the window scroll
    //$(id).style.top = ''+(((windowHeight/2)-(divHeight/2)))+'px';
    //$(id).style.left = ''+(((windowWidth/2)-(divWidth/2)))+'px';
}

function bringToTheMiddleOfTheScreen(id)
{  

    if(!$(id))
        return false;
        
    var windowWidth = GetWindowWidth();
    
    var windowHeight = GetWindowHeight();
    
    var divWidth = $(id).clientWidth;
    
    var divHeight = $(id).clientHeight;
    
    //To center element to a fixed position irrespective of the window scroll
    $(id).style.top = ''+(((windowHeight/2)-(divHeight/2)))+'px';
    $(id).style.left = ''+(((windowWidth/2)-(divWidth/2)))+'px';
    
    
}


function centerMsgDiv(id)
{
	centerDiv(id);
}

function centerEditDiv(id)
{
    centerDiv(id);
    return true;
}


function copyToClipboard(text)
{
	if (window.clipboardData) window.clipboardData.setData("Text", text);
   	else if (window.netscape) {
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		
		var clip = 
Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
   		if (!clip) return false;
		var trans = 
Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return false;
		trans.addDataFlavor('text/unicode');
		var str = new Object();
		var len = new Object();
		var str = 
Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
		str.data=text;
		trans.setTransferData("text/unicode",str,text.length*2);
		var clipid=Components.interfaces.nsIClipboard;
		if (!clipid) return false;
		clip.setData(trans,null,clipid.kGlobalClipboard);
	}
	return false;
	
}

function getScrollStats()
{
	var scrollLeft = 0;
	var scrollTop = 0;
	if (window.pageYOffset){  
	scrollTop = window.pageYOffset 
	} else if(document.documentElement && document.documentElement.scrollTop){ 
		scrollTop = document.documentElement.scrollTop; 
	} else if(document.body){ 
		scrollTop = document.body.scrollTop; 
	} 

	if(window.pageXOffset){ 
		scrollLeft=window.pageXOffset 
	} else if(document.documentElement && document.documentElement.scrollLeft){ 
		scrollLeft=document.documentElement.scrollLeft; 
	} else if(document.body){ 
		scrollLeft=document.body.scrollLeft; 
	}
    var retArray = Array();
	retArray[0] = scrollLeft;
	retArray[1] = scrollTop;

	return retArray;
}

function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;

	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac

		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;

	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari

		yWithScroll = document.body.offsetHeight < window.innerHeight?window.innerHeight:document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth < window.innerWidth?window.innerWidth: document.body.offsetWidth;
		
		if(yWithScroll < document.body.scrollHeight)
			yWithScroll = document.body.scrollHeight;
		if(xWithScroll < document.body.scrollWidth)
			xWithScroll = document.body.scrollWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);

	return arrayPageSizeWithScroll;
}

// function  GetWindowWidth return the client browser width
//modified by : Manish Sharma
// modified on : 10-03-2009
function GetWindowWidth() { 
 
//return screen.width;

  //return window.innerWidth||
    //document.documentElement&&document.documentElement.clientWidth||
    //document.body.clientWidth||0;

var windowWidth = 0;
        if (typeof(window.innerWidth) == 'number') {
            windowWidth = window.innerWidth;
        }
        else {
            if (document.documentElement && document.documentElement.clientWidth) {
                windowWidth = document.documentElement.clientWidth;
            }
            else {
                if (document.body && document.body.clientWidth) {
                    windowWidth = document.body.clientWidth;
                }
            }
        }
        return windowWidth;
}

// function  GetWindowHeight return the client browser height
//modified by : Manish Sharma
// modified on : 10-03-2009

function GetWindowHeight() { 

  //return window.innerHeight||
    //document.documentElement&&document.documentElement.clientHeight||
    //document.body.clientHeight||0;

var windowHeight = 0;
        if (typeof(window.innerHeight) == 'number') {
            windowHeight = window.innerHeight;
        }
        else {
            if (document.documentElement && document.documentElement.clientHeight) {
                windowHeight = document.documentElement.clientHeight;
            }
            else {
                if (document.body && document.body.clientHeight) {
                    windowHeight = document.body.clientHeight;
                }
            }
        }
        return windowHeight;
}


/**
 * Called when a max3 is to be downloaded.
 * Hides download icon as appropriate according to number of downloads remaining.
 *
 * @param A       a     A element.
 * @param string  url   URL to use to download max3.
 * @param string  num   Number of download element.
 */
function downloadMax3(url, num)
{
   var elem = $('numDownloads' + num);
   var numDownloads = 0;
   var allow = false;

   if (elem)
   {
      numDownloads = parseInt(elem.value, 10);

      if (numDownloads)
      {
         numDownloads--;
         allow = true;
         elem.value = numDownloads;
         elem = $('link' + num);

         if (elem)
         {
            elem.title = numDownloads + ' downloads remaining.';
         }
      }
   }

   if (numDownloads <= 0)
   {
      elem = $('link' + num);

      if (elem)
      {
         elem.style.display = 'none';
      }
   }

   if (allow)
   {
      document.location = url;
   }
}

/**
	Following function shifts the selected options from the 'from' drop down to 'to' drop down.
*/
function shiftSelectedItems(from,to){
		var fromDD = $(from);
		var toDD = $(to);	
		var newOption;
		
		for(var i=0;i<fromDD.options.length;i++)
		{
			
			if(fromDD.options[i].selected && fromDD.options[i].value)
			{
				toDD.options[toDD.options.length] = new Option(fromDD.options[i].text,fromDD.options[i].value);
				toDD.options[toDD.options.length-1].setAttribute('id', fromDD.options[i].getAttribute('id'));
				toDD.setAttribute('OnDblClick', "shiftSelectedItems('"+to+"','"+from+"');composeSendToList();");
				fromDD.removeChild(fromDD.options[i]);
				--i;
			}
		}
}

/**
	Following function composes a comma separated string from the options added in the Send to drop down on
	forward max3 page and assigns that string to the hidden variable 'sendTo'
*/
function composeSendToList()
{
	var reciverList = $('reciverList');
	var emailIds = Array();
	var contactIds = Array();
	for(var i=0;i<reciverList.options.length;i++)
	{
		emailIds[i] = reciverList.options[i].id;
		contactIds[i] = reciverList.options[i].value;
	}
	$('sendTo').value = emailIds.join(",");
	$('selectedRecivers').value = contactIds.join(",");
	
	
}

/**
	Following function checks wether the option with the given value exists in the given drop down or not.
*/
function optionPresentIn(dropDownObjId,val)
{
	var dropDown = $(dropDownObjId);
	if(dropDown && dropDown.options)
	{
		for(var i=0;i<dropDown.options.length;i++)
		{
			if(dropDown.options[i].value == val)
				return true;
		}
	}
	return false;
}

/**
	Following function loads the given flash file on the max3 home page.
*/
function loadHomeFlash(flashFile)
{
	wasp_loadAndPlay(window.MOJAVI_BASE_URL+'/flash/'+escape(flashFile));
}


function playFlashOnHomePage(flash,elementId)
{
	var FO1 = {	movie:window.MOJAVI_BASE_URL+"/includes/jquery/jquery/flvplayer.swf",width:"320",height:"260",majorversion:"7", build:"0",bgcolor:"#FFFFFF",allowfullscreen:"true",flashvars:"file="+window.MOJAVI_BASE_URL+"/flash/"+escape(flash)+"&showicons=false&autostart=false" };
	UFO.create(FO1, elementId);
	$(elementId).style.display = '';
}

function decrementNumDownloads(num)
{
	
	var elem = $('numDownloads' + num);
	var txt_dnlds = $('txt_numdnlds');
	var dnldlink = $('dnldlink');
	var dnldsRemaining = elem.value;

	if(txt_dnlds)
		txt_dnlds.innerHTML = ((dnldsRemaining>0)?dnldsRemaining:'no') + '';

	if(dnldsRemaining<=0 && dnldlink)
		dnldlink.disabled = true;

}	

function hideAllElements(tagName)
{
	var allObjects = document.getElementsByTagName(tagName);
    var nameParts, totalParts;
	if(allObjects )
	{
		for(var i=0;i<allObjects .length;i++)
		{
            nameParts = allObjects[i].name.split("_");
            totalParts = nameParts.length;
            if(nameParts[totalParts-1]!='required')
			    allObjects[i].style.display = 'none';
		}
	}
}
function showAllElements(tagName)
{
	var allObjects = document.getElementsByTagName(tagName);
	if(allObjects )
	{
		for(var i=0;i<allObjects .length;i++)
		{
			allObjects[i].style.display = '';
			
		}
	}
}

function displayHomeLoginLink(display1)
{
    if(display1)
        $("homeLoginForm").display= 'block';
    else
        $("homeLoginForm").display= 'none';
}

function hideHomeLoginForm(hide)
{
    if(hide)
        $("homeLoginForm").display= 'none';
    else
        $("homeLoginForm").display= 'block';
        
}

function edit(id)
{
    $('editableContentContainer').style.display = '';
	tinyMCE.getInstanceById('con').getBody().innerHTML = $('editContent'+id).innerHTML;
    window.coni = id;
    centerEditDiv('editableContentContainer');
}

function hideEdit()
{
    $('editableContentContainer').style.display = 'none';
	turnOffProcessIndicator();
}

function showEditInProgress()
{
     $('editableContentContainer').style.display = 'none';
	 centerDiv('editableContentContainer');
     turnOnProcessIndicator('<b>Saving content...please wait..</b>');
}

function showTextEditFailureMessage()
{
     $('editableContentContainer').style.display = 'none';
     smdAlert('SMD Alert', '<span class=formerror>Could not save the content. Please try again.</span>');
}

function addCallbackToWindowScrollEvent(callback)
{
    var existingFun = window.onscroll;

    window.onscroll = function() {
    if(existingFun)
        existingFun();
        eval(callback);
    
    };
}

function addCallbackToWindowResizeEvent(callback)
{     
    var existingFun = window.onresize;

    window.onresize = function() {
    if(existingFun)
        existingFun();
        eval(callback);
    
    };
}

/**function addCallbackToWindowLoadEvent(callback)
{
    var existingFun = window.onload;
    window.onload = function() {
		if(existingFun)	
	        existingFun();
        eval(callback);
    };
}
*/

function addCallbackToWindowLoadEvent(callback)
{
    winloadFuns = winloadFuns + callback + ';';
}


function setCursorStyle(style)
{
    document.body.style.cursor = style;
}

function showSpecifiedElements(tagName, idPrefix, separator)
{
    var allObjects = document.getElementsByTagName(tagName);
    var idParts;
    if(allObjects )
    {
        for(var i=0;i<allObjects .length;i++)
        {
            idParts = allObjects[i].id.split(separator);
            if(idParts[0] == idPrefix)
                allObjects[i].style.display = '';
            
        }
    }
}

function hideSpecifiedElements(tagName, idPrefix, separator)
{
    var allObjects = document.getElementsByTagName(tagName);
    var nameParts, totalParts, idParts;
     
    if(allObjects )
    {
        for(var i=0;i<allObjects .length;i++)
        {
            idParts = allObjects[i].id.split(separator);

            if(idParts[0] == idPrefix)
            {
                if(allObjects[i].name)
                {
                    nameParts = allObjects[i].name.split("_");
                    totalParts = nameParts.length;
                    if(nameParts[totalParts-1]!='required')
                        allObjects[i].style.display = 'none';
                }
                else
                    allObjects[i].style.display = 'none';
            }
           
        }
    }
}

function disableUserActions()
{

	var theBody = document.getElementsByTagName('body')[0];
	var opacityRatio;
	if(isWin)
		opacityRatio = 60;
	else
		opacityRatio = 40;
	
	if(!$('actnBlckr'))
	{
		var actionBlckDv = document.createElement('DIV');
		actionBlckDv.setAttribute('id', 'actnBlckr');
		
		theBody.appendChild(actionBlckDv);

		actionBlckDv.setAttribute('style', 'display: none;position: absolute; top: 0px; left: 0px; background-color: #fff; filter:alpha(opacity='+opacityRatio+'); -moz-opacity:.'+opacityRatio+'; opacity:.'+opacityRatio+';');
		/** IE patches */
		actionBlckDv.style.position = isIE6?"absolute":"fixed";
		actionBlckDv.style.top = "0px";
		actionBlckDv.style.left = "0px";
		actionBlckDv.style.backgroundColor = "#999";
		actionBlckDv.style.filter = "alpha(opacity="+opacityRatio+");";
		actionBlckDv.style.zIndex = "999";   
		/** IE patches */

	}
	
	/**
	var pageSize = getPageSizeWithScroll();
	var width = pageSize[0];
	var height = pageSize[1];
	*/
	$('actnBlckr').style.display = '';
	$('actnBlckr').style.width = GetWindowWidth() + 'px';
	$('actnBlckr').style.height = GetWindowHeight() + 'px';
	
	if(isIE6){
		fixActionBlockerInIe6();
		addCallbackToWindowScrollEvent(" fixActionBlockerInIe6(); ");
	}
}

function fixActionBlockerInIe6()
{
	var pageScrollStats = getScrollStats(); 
	if($('actnBlckr'))
		$('actnBlckr').style.top = pageScrollStats[1] + 'px';       
    
}

function fixTopBarInIe6()
{
   return true; // Added by ajay in order to fix top bar for IE6
	var pageScrollStats = getScrollStats(); 
	if($('ucf'))
     {       
		$('ucf').style.top =  pageScrollStats[1] + 'px';
     }
}

function disableUserActionsInElement(elem)
{

	var theBody = $(elem);

	var elemTop = getElementTop(elem);
	var elemLeft = getElementLeft(elem);

	var elemWidth = getElementWidth(elem);
	var elemHeight = getElementHeight(elem);

	var opacityRatio;
	if(isWin)
		opacityRatio = 60;
	else
		opacityRatio = 40;
    var blockerName = 'elmActnBlckr' + elem;


	if(!$(blockerName))
	{
		var actionBlckDv = document.createElement('DIV');

		actionBlckDv.setAttribute('id', blockerName);
		
		theBody.appendChild(actionBlckDv);
		actionBlckDv.innerHTML = "<img src = '/images/loadingBar.gif' valign='middle' style='margin-top: "+ Math.round(elemHeight/2) +"px;' />";

		actionBlckDv.setAttribute('style', 'display: none;position: absolute; top: 0px; left: 0px; background-color: #cccccc; filter:alpha(opacity='+opacityRatio+'); -moz-opacity:.'+opacityRatio+'; opacity:.'+opacityRatio+';');
		/** IE patches */
		actionBlckDv.style.position = "absolute";
		actionBlckDv.style.border = "1px dashed #000000";
		actionBlckDv.style.top = elemTop + "px";
		actionBlckDv.style.left = elemLeft + "px";
		actionBlckDv.style.backgroundColor = "#999";
		actionBlckDv.style.filter = "alpha(opacity="+opacityRatio+");";
		actionBlckDv.style.zIndex = "499";
		actionBlckDv.style.textAlign = "center";
		/** IE patches */

	}

	$(blockerName).style.display = '';
	$(blockerName).style.width = elemWidth + 'px'; 
	$(blockerName).style.height = elemHeight + 'px';
}

function enableUserActionsInElement(elem)
{
	var blockerName = 'elmActnBlckr' + elem;
	if($(blockerName))
		$(blockerName).style.display = 'none';
}

function enableUserActions()
{
	if($('actnBlckr'))
		$('actnBlckr').style.display = 'none';
}

function smdAlert(heading, msg)
{

	if(heading == 'SMD Alert')
		heading = 'max3 Alert';
    if($('smdAlert'))
    {
		setSmdAlertButtonCaption(" Ok ");
        $('smdAlert').style.display = '';
        $('smdAlertMessage').innerHTML = msg;
        $('smdAlertHeading').innerHTML = heading;
		showSmdAlertButton();
		if($('smdAlert_Ok') && $('smdAlert_Ok').style.display!='none')
	        $('smdAlert_Ok').focus();
		disableUserActions();
        centerDiv('smdAlert');
		window.focus();
    }
}

function turnOnCloseableAlert(heading, message){
  smdMessage(heading, message);    
  $('closeSmdAlert').style.display = '';  
}

function turnOffCloseableAlert(){
 enableUserActions();
 $('smdAlert').style.display = 'none'; 
 $('closeSmdAlert').style.display = 'none'; 
}

function smdMessage(heading, msg)
{
	if(heading == 'SMD Alert')
		heading = 'max3 Alert';
    if($('smdAlert'))
    {
		setSmdAlertButtonCaption(" Ok ");
		hideSmdAlertButton();

        $('smdAlert').style.display='';
        $('smdAlertMessage').innerHTML = msg;                
        $('smdAlertHeading').innerHTML = heading;
        
		disableUserActions();
        centerDiv('smdAlert');
		window.focus();
    }
}

function setSmdAlertWidth(width)
{
	$('smdAlert').style.width = width;
}

/**
* This function is used to increase with of alert box 
* @author Kapil Sakhare
* @param mixed Width
*/
function setSmdAlertBoxCloseWidth(width)
{
	$('smdAlertBox').style.width = width;//800px
}

function isSmdAlertOn()
{
	return $('smdAlert').style.display == '';
}

function setSmdAlertButtonCaption(cap)
{
	if($('smdAlert_Ok'))
	{
		$('smdAlert_Ok').value = cap;
	}
}

function hideSmdAlertButton()
{
	if($('smdAlert_Ok_Container'))
	{
		$('smdAlert_Ok_Container').style.display = 'none';
	}
}

function showSmdAlertButton()
{
	if($('smdAlert_Ok_Container'))
		$('smdAlert_Ok_Container').style.display = '';
}

function switchOffSmdAlert()
{
	enableUserActions();
    if($('smdAlert'))
    {
		$('smdAlert').style.display = 'none';
    }
}

function switchOnSmdAlert()
{
    if($('smdAlert'))
    {
		disableUserActions();
        $('smdAlert').style.display = '';
		centerDiv('smdAlert');
    }
}

function turnOnProcessIndicator(msg)
{
   if($('smdProcessIndicator'))
   {
	   disableUserActions();
		var  settings = {
			  tl: { radius: 8 },
			  tr: { radius: 8 },
			  bl: { radius: 8 },
			  br: { radius: 8 },
			  antiAlias: true,
			  autoPad: false
		};
	
		$('smdProcessIndicator').style.display = '';
        $('smdProcessIndicator').innerHTML = '<div id="processIndicatorMessage" ><div style="padding: 10px;">'+msg+'</div></div>';
	    
		centerDiv('smdProcessIndicator');
		
		var processIndicatorCorner = $('processIndicatorMessage');
		var processIndicatorCornersObj = new curvyCorners(settings, processIndicatorCorner);
		processIndicatorCornersObj.applyCornersToAll();
		window.curvyCornersAppliedToProcessIndicator = true;
   } 
}

function turnOffProcessIndicator()
{
   enableUserActions();
   if($('smdProcessIndicator'))
   {
        $('smdProcessIndicator').style.display = 'none';
   } 
}

function addMoreFileInputsTo(elem, inputName, size, className)
{
    var inputContainer = $(elem); 
    var inputContainer = $(elem);

    //Collect file inputs
    var fileInputs = getFileInputs(elem);
    
    //Attach new file input
    var newFileInputHolder = document.createElement('DIV'); 
    var divId = "fileInputHolder_" + (fileInputs.length+1);
    newFileInputHolder.setAttribute("id", divId); 
    newFileInputHolder.setAttribute("class", "row"); 
    var newFileInputHolderNumber = document.createElement('SPAN'); 
    newFileInputHolderNumber.innerHTML = "#"+(fileInputs.length+1)+" ";
    newFileInputHolderNumber.setAttribute("id", "fileInputNo_"+(fileInputs.length+1));
    var newFileInput = document.createElement('INPUT');
    newFileInput.setAttribute("type", "file");
    newFileInput.setAttribute("name", inputName);
    newFileInput.setAttribute("size", size);
    newFileInput.setAttribute("class", className);
    
    //Link to remove the input
    var newRemoveInputLink = document.createElement('a');
    var newRemoveInputLinkTitle = document.createTextNode(' remove');
    newRemoveInputLink.setAttribute("href", "javascript: detachElement('"+elem+"', '"+divId+"'); resetFileInputNumbers('"+elem+"'); ");
    
    newRemoveInputLink.appendChild(newRemoveInputLinkTitle);
    
    newFileInputHolder.appendChild(newFileInputHolderNumber);
    newFileInputHolder.appendChild(newFileInput);
    newFileInputHolder.appendChild(newRemoveInputLink);
    inputContainer.appendChild(newFileInputHolder);
    
    
}

function detachElement(parentId, childId)
{
    var parent = $(parentId);
    var child = $(childId);
    if(parent && child)
    {
        parent.removeChild(child);
    }
}

function getFileInputs(elem)
{
    var inputContainer = $(elem);
    var currentInputs = inputContainer.getElementsByTagName("input");
    
    //Collect file inputs
    var fileInputs = new Array();
    for(var i=0; i<currentInputs.length; i++)
    {
        if(currentInputs[i].type=='file')
            fileInputs[fileInputs.length] = currentInputs[i]; 
    }
    
    return fileInputs;
}

function resetFileInputNumbers(elem)
{
    var inputContainer = $(elem);
    var inputHolders = inputContainer.getElementsByTagName("div");
    
    //If any DIV is present
    if(inputHolders)
    {
        for(var i=0; i<inputHolders.length; i++)
        {
            //check if the DIV id matches with the predefined format.
            if(inputHolders[i].id)
            {
                var idParts = inputHolders[i].id.split("_");
                
                if(idParts[0] == "fileInputHolder")
                {
                    //Now check any span is there containing the file input number.
                     var spans = inputHolders[i].getElementsByTagName("span");
                     if(spans)
                     {
                         for(var j=0; j<spans.length; j++)
                         {
                            var spanIdParts = spans[j].id.split("_");
                            if(spanIdParts[0] == "fileInputNo")
                            {
                               spans[j].innerHTML = "#"+(i+1)+" "; 
                            }
                         }
                     }
                }
            }
        }
    }
}

function textLimit(field, maxlen) {

    var lengthExceeded = false;
    if (field.value.length > maxlen)
    {
         field.value = field.value.substring(0, maxlen);
         lengthExceeded = true;
    }
    
    if (lengthExceeded)
    {
         smdAlert('SMD Alert', '<span class="formerror">You are exceeding the maximum allowed character size for the review!</span>');
         return false;
    }
    return true;
    
}


function incrementMax3Clicks(scriptName, uuid)
{
	 var url = scriptName+'/default/incrementClicks/uuid/'+ uuid;

	 //create a temporary DIV element to contain the clicks increment action response. This is useless but needed for AJAX call
	 if(!$('clicksIncrementResponse'))
	 {
		 var tempDiv = document.createElement('DIV');
		 tempDiv.setAttribute('id', 'clicksIncrementResponse');		 
		 tempDiv.style.display = 'none';

		 if(isMozilla)
			document.childNodes[1].appendChild(tempDiv);	
 		 else
			document.childNodes[0].childNodes[1].appendChild(tempDiv);
	 }

	 new Ajax.Updater('clicksIncrementResponse',url,
					 {
					   asynchronous:true, 
					   evalScripts:true  
					 }
					); 
}

function Get_Cookie( check_name ) {

	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}

function Set_Cookie( name, value, expires, path, domain, secure ) {

	var today = new Date();
	today.setTime( today.getTime() );

	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function areCookiesEnabled()
{
	Set_Cookie( 'test', 'none', '', '/', '', '' );

	if ( Get_Cookie( 'test' ) )
	{	
		cookie_set = true;
		Delete_Cookie('test', '/', '');
		
	}
	else
	{
		cookie_set = false;
	}

	return cookie_set;
}

function turnOffEditableTextFields()
{
	var editableFields = document.getElementsByClassName('editableContentOn');
	if(editableFields)
	{
		for(var i = 0; i<editableFields.length; i++)
		{
			editableFields[i].className = 'editableContent';
			editableFields[i].alt = '';
			editableFields[i].title = '';
		}
	}

}

function turnOnEditableTextFields()
{
	var editableFields = document.getElementsByClassName('editableContent');
	if(editableFields)
	{
		for(var i = 0; i<editableFields.length; i++)
		{
			editableFields[i].className = 'editableContentOn';
			editableFields[i].alt = 'Double click to edit the content';
			editableFields[i].title = 'Double click to edit the content';
		}
	}

}

function numbersOnly(e){
    var unicode=e.charCode? e.charCode : e.keyCode   
    if (unicode!=8 && unicode!=13 && unicode!=46 ){ //if the key isn't the backspace key  or Enter Key or dot (which we should allow)
        if (unicode<48||unicode>57) //if not a number
            return false //disable key press
    }
}

function hideScrolls()
{
	document.body.style.overflow='hidden';
}

function showScrolls()
{
	if(!isIE)
		document.body.style.overflow='scroll';
}

function setActualRanking(trackId, rank)
{
      if(!window.actualRankings)
        var actualRankings = new Array();
        
      window.actualRankings[trackId] = rank;

}

function getActualRanking(trackId)
{
    if(window.actualRankings)
    {
       if(window.actualRankings[trackId])
            return window.actualRankings[trackId];
    }
    return "";
    
}

function setRankingImageView(to, rankingImagePrefix)
{
	if(to % 0.5 != 0)
		to = Math.round(to);

	var rankingimage_src = Array();
	for(var j=1;j<=5;j++)
		rankingimage_src[j+''] = window.starNotSelected.src;

	for(var i=0;i<=to;i++)
	{
		if((i + 0.5 ) == to)
			rankingimage_src[i+1+''] = window.starHalfSelected.src;

		rankingimage_src[i+''] = window.starFullSelected.src;
	}

   if(document.images[rankingImagePrefix + '1'])	
	   document.images[rankingImagePrefix + '1'].src = rankingimage_src['1'];
   if(document.images[rankingImagePrefix + '2'])	
	   document.images[rankingImagePrefix + '2'].src = rankingimage_src['2'];
   if(document.images[rankingImagePrefix + '3'])	
	   document.images[rankingImagePrefix + '3'].src = rankingimage_src['3'];
   if(document.images[rankingImagePrefix + '4'])	
	   document.images[rankingImagePrefix + '4'].src = rankingimage_src['4'];
   if(document.images[rankingImagePrefix + '5'])	
	   document.images[rankingImagePrefix + '5'].src = rankingimage_src['5'];
}

function updateCartItemCount(itemCount, cookieName)
 {      
    var domainName = document.domain;
    var pos = 0;
     
	pos = domainName.lastIndexOf('.', domainName.lastIndexOf('.', domainName.length)-1);
    mainDomain = domainName.slice( pos );    
    
    $('cartItemCount').innerHTML = itemCount;    
    setCookie(cookieName, itemCount, '' , '/', mainDomain  ) ;                  
 }
 
 function updateUserForwardPoints(downloadCount, cookieName)
 {      
    var domainName = document.domain;
    var pos = 0;

    pos = domainName.lastIndexOf('.', domainName.lastIndexOf('.', domainName.length)-1);
    mainDomain = domainName.slice( pos );  
    setCookie(cookieName, downloadCount, '' , '/', mainDomain  ) ;                  
 }

  function updatePurchaseDownloadAlertCookie()
 {      
    var domainName = document.domain;
    var pos = 0;

    pos = domainName.lastIndexOf('.', domainName.lastIndexOf('.', domainName.length)-1);
    mainDomain = domainName.slice( pos );  
    setCookie('downloaderInstalled', 'true', '' , '/', mainDomain  ) ;                  
 }
 
 function setCookie(name, value, expires, path, domain, secure) 
 {  
       
    var domainName = document.domain;
    var pos = 0;
    pos = domainName.lastIndexOf('.', domainName.lastIndexOf('.', domainName.length)-1);
    domain = domainName.slice(pos);
    
    expires instanceof Date ? expires = expires.toGMTString() : typeof(expires) == 'number' && (expires = (new Date(+(new Date) + expires * 1e3)).toGMTString());
    var r = [name + "=" + escape(value)], s, i;
    for(i in s = {expires: expires, path: path, domain: domain}){
        s[i] && r.push(i + "=" + s[i]);
    }
   return  secure && r.push("secure"), document.cookie = r.join(";"), true;     
}

function getCookie (name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen)
     {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return getCookieVal(j);
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
    }
    return 0;
}

function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1)
     endstr = document.cookie.length;
     
    return unescape(document.cookie.substring(offset, endstr));
}

function setViewCartItemCount(cookieName)
 {
    if($('cartItemCount'))
    {
        $('cartItemCount').innerHTML = getCookie(cookieName);   
    }
 }

 function setForwardPointCount(cookieName)
 {
    if($('fpTip'))
    {
        $('fpTip').innerHTML = getCookie(cookieName);   
    }
 }
    
function getSpecifiedElements(tagName, prefix, separator)
{
    var allObjects = document.getElementsByTagName(tagName);
    var idParts;
	var retObjs = new Array();

    if(allObjects )
    {
        for(var i=0;i<allObjects .length;i++)
        {
            idParts = allObjects[i].id.split(separator);
            if(idParts[0] == prefix)
                retObjs[retObjs.length] = allObjects[i];
            
        }
    }

	if(retObjs.length > 0)
		return retObjs;
	else
		return NULL;
}

function toggleLinkTitle(linkId, title1, title2)
{
  var linkTitle = $(linkId).innerHTML;

  if(linkTitle == title1)
  {
	  $(linkId).innerHTML = title2;
	  return true;
  }

  $(linkId).innerHTML = title1;
  return true;
}

function toggleElementClass(elemId, class1, class2)
{
  var curCls = $(elemId).className;

  if(curCls == class1)
  {
	  $(elemId).className = class2;
	  return true;
  }
  $(elemId).className = class1;
  return true;
}

function addToVisitedMax3(url)
 {
 var newUrl = url;
/*
    var domainName = document.domain;    
    newUrl = 'http://' + domainName + url;
*/
        
    new Ajax.Updater('',newUrl,
                     {
                       asynchronous:true, 
                       evalScripts:true  
                     }
                    );       
    
 }


function hideAllDlinkCodeToolTips(){

	$$('dLinkAnchor').each( function(element){
															element.prototip.hide();
													    }
					);

	$$('dLinkIcon').each( function(element){
															element.prototip.hide();
													    }
					);
}



function smdDeletConfirmation(strHeading, strMessage, strDeleteAction )
 {   
     disableUserActions();     
     var heading = strHeading;
     var url = strDeleteAction;
     
     if(heading == '')
     {
        heading = 'Delete Confirmation';
     }
        
     document.getElementById('smdDeleteConfirmationBox').style.display = '';
     document.getElementById('smdFloatingMessageHeading').innerHTML = heading;
     document.getElementById('smdFloatingMessage').innerHTML = strMessage; 
     centerDiv('smdDeleteConfirmationBox');
     //var eff = new Effect.Shake('smdDeleteConfirmationBox',{});
        
     document.getElementById('smdDeleteConfirmed').onclick = function()
                                                                {
                                                                    this.blur();
                                                                    var t = new Effect.Fade('smdDeleteConfirmationBox',{});
                                                                    location.href = strDeleteAction;  
                                                                    enableUserActions();                                                                                                                                                 
                                                                    return false;
                                                                } 
 }

function clearLoginJoinResponses()
{
	//clear response divs
	if($('divLoginResponse'))
	    $('divLoginResponse').innerHTML='';

	if($('divSignUpResponse'))
	    $('divSignUpResponse').innerHTML=''; 

	if($('divPwdFeedback'))
		$('divPwdFeedback').innerHTML=''; 
}

function linkForLogin()
{
	clearLoginJoinResponses();

	var forPwdWasOpen = $('divForgotPwdForm')?($('divForgotPwdForm').style.display != 'none'):false;
	//hide other boxes
	if($('divSignUpBox'))
	    $('divSignUpBox').style.display='none';
	if($('divForgotPwdForm'))
	    $('divForgotPwdForm').style.display='none';

	if($('homeLoginForm'))
	   $('homeLoginForm').style.display='';

	if($('divLoginBox').style.display == 'none' || forPwdWasOpen)
	    new Effect.BlindDown('divLoginBox',{});
	else
		new Effect.BlindUp('divLoginBox',{});
}
 
function linkForSignUp()
{
   clearLoginJoinResponses();

   //hide other boxes
   if($('divLoginBox'))
	   $('divLoginBox').style.display='none';
   if($('divForgotPwdForm'))
	    $('divForgotPwdForm').style.display='none';

   new Effect.toggle('divSignUpBox','blind',{});  
}

function linkForNonUserForShare(url)
{
	document.location.href=url;
}

function linkForForgotPwd()
{
   clearLoginJoinResponses();

   //hide other boxes

   if($('homeLoginForm'))
	   $('homeLoginForm').style.display='none';
   if($('divSignUpBox'))
	    $('divSignUpBox').style.display='none';

   new Effect.toggle('divForgotPwdForm','blind',{});  
}

/*
#################################################################################################################################
# Function Name : checkPayapalAddress()
# Created By : Manish Sharma
# Created On : 14 Feb 2009
# Parmeter : actionName - action name for ajax operation
#            queryString - all parameter string which is required for opertaion
#            updatedDiv - div id whcih is updated with ajax response
# Description : function to check the payapal address is exist in user table or not if not then return _paypalinfo partial on pay 
#               me page when user click on the REQUEST PAYMENT button
#################################################################################################################################
*/ 
 function checkPayapalAddress(actionName, queryString, updatedDiv)
 {
     //alert(actionName +'**' +queryString +'**' +updatedDiv);
        setCursorStyle('wait');
        //$('indicator').innerHTML = 'loading data...please wait...';
        var url = '/account/' + actionName + queryString;
     
        new Ajax.Updater(updatedDiv, url,
                                                {               
                                                    asynchronous:true,
                                                    evalScripts:true, 
                                                    method:'get', 
                                                    onComplete:function(request,json)
                                                        {
                                                           //alert(request.responseText); 
                                                            setCursorStyle('default');
                                                                                         
                                                        }
                                                                                     
                                                }
                         );                              
 
 
 }
/*
#################################################################################################################################
# Function Name : savePaypalAddress()
# Created By : Manish Sharma
# Created On : 14 Feb 2009
# Parmeter : actionName - action name for ajax operation
#            queryString - all parameter string which is required for opertaion
#            updatedDiv - div id whcih is updated with ajax response
# Description : function to save payapal address in user table with validation from pay me page when user click on the 
#               REQUEST PAYMENT button
#################################################################################################################################
*/  
function savePaypalAddress(actionName, queryString, updatedDiv)
{
   var paypalEmail = $('paypalEmail').value;
   var confirmPaypalEmail = $('confirmPaypalEmail').value;
   var taxid = $('taxid').value;
   
   var redirectURL = "/account/summary";
  
   if(paypalEmail=='')
    {
        smdAlert('Error', 'Please enter paypal account email.');
        return false;
    }
   
   if(!validateEmails(paypalEmail,''))
    {
        return false;
    }
    
   if(confirmPaypalEmail=='')
    {
        smdAlert('Error', 'Please enter confirm paypal account email.');
        return false;
    }
   
  if(!validateEmails(confirmPaypalEmail,''))
    {
        return false;
    }
    
  if(paypalEmail!=confirmPaypalEmail)
    {
      smdAlert('Error', '"Paypal account email" and "confirm paypal account email" shuold same.');
      return false;
    }  

   if(taxid=='')
    {
        smdAlert('Error', 'Please enter social security number or tax id.');
        return false;
    }
   
   
    
    var queryString =  '?paypalEmail='+$('paypalEmail').value+'&confirmPaypalEmail='+$('confirmPaypalEmail').value+'&taxid='+$('taxid').value ; 
     //alert(actionName +'**' +queryString +'**' +updatedDiv);
    setCursorStyle('wait');
    var url = '/account/' + actionName + queryString;
        
        new Ajax.Updater(updatedDiv, url,
                                                {               
                                                    asynchronous:true,
                                                    evalScripts:true, 
                                                    method:'get',
                                                    onComplete:function(request,json)
                                                        {
                                                           //alert(request.responseText); 
                                                           setCursorStyle('default');
                                                           //document.location.href=redirectURL;                              
                                                        }                             
                                                }
                         );                              
 
 
 } 

  function removeNL(s){  
 /* Madan K
  ** Remove NewLine, CarriageReturn and Tab characters from a String
  **   s  string to be processed
  ** returns new string
  */

  return s.replace(/[\n\r\t]/g,''); 
}

// detect client browser and if safri then show the error

function fnClientBrowserType()
{
   var ua = navigator.userAgent.toLowerCase();
   if (ua.indexOf('safari/') != -1)
   {
        //alert(" Your browser may suffer from erratic behavior. We suggest you use Firefox. ")
        enableUserActions();
        return false;
   }

}

function warnForSafari()
{
   var ua = navigator.userAgent.toLowerCase();
   if (ua.indexOf('safari/') != -1)
   { 
        alert(" Your browser may suffer from erratic behavior. We suggest you use Firefox"); 
   }
}
// toggle recent max3 list up/down
function toggle_RecentList(id) {
	var el = $(id);
	if (el.className=='recentMax3_toggle_up') {
		el.className='recentMax3_toggle_down';
		Effect.BlindDown('recentTrackView', { duration: .25 });
	} else {
		el.className='recentMax3_toggle_up';
		Effect.BlindUp('recentTrackView', { duration: .25 });
	}
}

