//search bar stuff
function menucolor( type )
{

	var defaultClass = "tdborder";
	var defaultClasa = "boxtitles";
	var fontClassOn = 'srchFontOn';

	var arrType = new Array();	

	arrType["aname"] = new Object();
	arrType["aname"].linkId 			= "artistLink";
	arrType["aname"].fontId 			= "artistFont";
	arrType["aname"].onClass 			= "srchArtistOn";
	arrType["aname"].backgroundColor	= "#FDE8D3";
	

	arrType["tname"] = new Object();
	arrType["tname"].linkId				= "albumLink";
	arrType["tname"].fontId 			= "albumFont";
	arrType["tname"].onClass 			= "srchAlbumOn";
	arrType["tname"].backgroundColor	= "#EDFCD1";

	arrType["sname"] = new Object();
	arrType["sname"].linkId				= "songLink";
	arrType["sname"].fontId 			= "songFont";
	arrType["sname"].onClass 			= "srchsongOn";
	arrType["sname"].backgroundColor	= "#E1D9EE";

	arrType["anamev"] = new Object();
	arrType["anamev"].linkId			= "videoLink";
	arrType["anamev"].fontId 			= "videoFont";
	arrType["anamev"].onClass 			= "srchVideoOn";
	arrType["anamev"].backgroundColor	= "#FCEAB8";
	
	//loop
	document.getElementById( arrType["sname"].linkId ).className = defaultClass;
	document.getElementById( arrType["tname"].linkId ).className = defaultClass;
	document.getElementById( arrType["anamev"].linkId ).className = defaultClass;
	document.getElementById( arrType["aname"].linkId ).className = defaultClass;

	document.getElementById( arrType["sname"].fontId ).className = defaultClasa;
	document.getElementById( arrType["tname"].fontId ).className = defaultClasa;
	document.getElementById( arrType["anamev"].fontId ).className = defaultClasa;
	document.getElementById( arrType["aname"].fontId ).className = defaultClasa;

	document.getElementById( arrType[type].linkId ).className = arrType[type].onClass;
	document.getElementById( arrType[type].fontId ).className = fontClassOn;
	document.getElementById( 'srchRowBg' ).style.backgroundColor = arrType[type].backgroundColor;
	document.getElementById( 'search-results' ).style.backgroundColor = arrType[type].backgroundColor;
	document.getElementById( 'srchType' ).value = type;

	gsc_emptyresults( document.getElementById( 'search-results' ) );
	
	//reinitiate search query
	__gsctimer.start();
	
	//focus on search box
	document.getElementById( 'fq' ).focus();
}



/***********************************************
* Tab Menu- By Alf Magne Kalleland www.dhtmlgoodies.com
* Script featured and available at Dynamic Drive: http://www.dynamicdrive.com/
* This notice must stay intact for use
***********************************************/
	
var topMenuSpacer = 5; // Horizontal space(pixels) between the main menu items	
var activateSubOnClick = true; // if true-> Show sub menu items on click, if false, show submenu items onmouseover
var leftAlignSubItems = false; 	// left align sub items t
var activeMenuItem = false;	// Don't change this option. It should initially be false
var activeTabIndex = -1;	// Index of initial active tab	(0 = first tab) - If the value below is set to true, it will override this one.


function showHide()
{
	if(activeMenuItem){
		activeMenuItem.className = 'inactiveMenuItem'; 	
		var theId = activeMenuItem.id.replace(/[^\d]/g,'');
		document.getElementById('submenu_'+theId).style.display='none';
	}

	
	activeMenuItem = this;		
	this.className = 'activeMenuItem';
	var theId = this.id.replace(/[^\d]/g,'');
	document.getElementById('submenu_'+theId).style.display='block';
	
}

function initMenu()
{
	
	var mainMenuObj = document.getElementById('mainMenu');
	var subMenuObj = document.getElementById('submenu'); //DD added line
	mainMenuObj.style.visibility=subMenuObj.style.visibility="visible"; //DD added line
	var menuItems = mainMenuObj.getElementsByTagName('A');
	
	if(document.all){
		mainMenuObj.style.visibility = 'hidden';
		document.getElementById('submenu').style.visibility='hidden';
	}
	
	
	var currentLeftPos = 30;
	for(var no=0;no<menuItems.length;no++){	
	
		menuItems[no].onclick = showHide; 
		
		currentLeftPos = currentLeftPos + menuItems[no].offsetWidth + topMenuSpacer;
		
		if(no==activeTabIndex){
			menuItems[no].className='activeMenuItem';
			activeMenuItem = menuItems[no];
		}else menuItems[no].className='inactiveMenuItem';
		
		if(!document.all)
			menuItems[no].style.bottom = '-1px';
		
	}		
	
	var mainMenuLinks = mainMenuObj.getElementsByTagName('A');
	
	var subCounter = 1;
	var parentWidth = mainMenuObj.offsetWidth;
	while(document.getElementById('submenu_' + subCounter)){
		var subItem = document.getElementById('submenu_' + subCounter);
		
		if( !leftAlignSubItems){
			var leftPos = mainMenuLinks[subCounter-1].offsetLeft;
			document.getElementById('submenu_'+subCounter).style.paddingLeft =  leftPos + 'px';
			subItem.style.position ='relative';
			leftPos += 30;
			subItem.style.paddingLeft =  leftPos + 'px';
			subItem.style.position ='static';
		}
		
		if(subCounter==(activeTabIndex+1)){
			subItem.style.display='block';
		}else{
			subItem.style.display='none';
		}
		
		subCounter++;
	}
	
	if(document.all){
		mainMenuObj.style.visibility = 'visible';
		document.getElementById('submenu').style.visibility='visible';
	}
	document.getElementById('submenu').style.display='block';
}

//------------------Popup-------------------------//
// Initialise popup pointer
var popupWin = null;

function openPopup(extra) {	
	var url = "player/player.php?" + extra ;
	
	if( !popupWin || popupWin.closed ) {
			//popupWin = window.open( url,'AlBawabaNetCast','width=330,height=700,status=0');	
		//popupWin=window.open(url, 'AlBawabaNetCast', "status=yes,menubar=no,scrollbars=no,resizable=1,directories=no,location=no,width=340 ,height=700" );
		
		popupWin = open(url, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=yes,width=340,height=700,left=0, top=0,screenX=0,screenY=0');
	
	} else { 
		popupWin.focus();
	}
}


function playSongFromSite(sid,type) {

	if( !popupWin || popupWin.closed ) {
		// The popup is closed so open it, set the song we want to play as a URL param
		//because we can't be sure when the flash will be ready to called
		openPopup( 'action=playSongFromSite&sid=' + sid + '&type=' + type);
		
	} else {
		popupWin.playSongFromParent(sid,type);
	}
}
///////////////////POPUP//////////////////////
function getPlaylists(sid,type){
	
	//empty the td ,that hold the inner html for the popup note. 
	if( popup_table ){	
		popup_table = '';
	}
		
    //empty the popup note every time you get the playlists
	document.getElementById("note").innerHTML='<div id="loading"></div>';
	
 
	//create XMLHttpRequest using createRequestObject function 
    var xmlhttp = createRequestObject();

	//set the URl the will use the GET method to get the playlist from the server 
    xmlhttp.open("GET","../services/popup/getplaylist.php",true);
    
    // check the state of request if its ready state(=4) and not url not found(=404)
    xmlhttp.onreadystatechange=	function() {
        if (xmlhttp.readyState==4) {
            if (xmlhttp.status!=404) {
				
				// create from type object
                var local = new Object();
				
				//save the returned array from the server  
                local=new Function("return " + xmlhttp.responseText)();
				
                if(local != 0){
					
					//check if the returned code != 100 (100 = failed msg)
					if(local['code'] !='100'){
						
						//if not error msg fetch the array element and send it to printOut that will print it in the popup note div
						var i=0;
						while(i<local.length)
						{
							printOut(local[i]['playlist_name'],local[i]['playlist_id'],sid,i+1,type);
							i++;
						}
						
					} else {
						// if the local['code'] mean that user not login print messages like (you have to login)  
						printLogout();	
					}
					
				} else {
					
					document.getElementById("note").innerHTML = '<span class= \"userinfo \" >You have not add any playlist to add 											                        										playlist <a href="playlist_manager.php" >click here</a> </span>';
				}
                
	    } else {
       		alert("Error, please try again");
    	}
            
  	  }
    };
    xmlhttp.send(null);
}
////////////////////////////////////////////////////////////////////////////////////////////////
function addToPlaylist(pl,sid,type)
{
	
	//create XMLHttpRequest using createRequestObject function 
    var xmlhttp = createRequestObject();
	language='en';
    
	//set the URl the will use the GET method
    var path= "../services/popup/addToPlaylist.php?pl="+ pl +"&sid="+ sid+"&type="+ type+"&language="+language;
	
	//set the URl that will use the GET method to get the playlist from the server
    xmlhttp.open("GET",path,true);
    
	// check the state of request if its ready state(=4) and not url not found(=404)
    xmlhttp.onreadystatechange=	function() {
        if (xmlhttp.readyState==4) {
            if (xmlhttp.status!=404) {
				
				// create from type object
                var local = new Object();
				
				//save the returned array from the server  
                returnMsg=new Function("return " + xmlhttp.responseText)();
                
				//print the return message in the note that song added or not
                document.getElementById("note").innerHTML = '<span class="userinfo">' + returnMsg['message'] + '</span>';
                
				//run the timer after finish the time period the note will disappear
                InitializeTimer();
                
       		} else {
				//if there an error like the link not found alert will be run for the user 
            	alert("Error,please try again");
	  		}
			
        }
    };
    xmlhttp.send(null);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
//used to create XMLHttpRequest object  
function createRequestObject() { 
	var req; 
	if(window.XMLHttpRequest){ 
		// Firefox, Safari, Opera... 
		req = new XMLHttpRequest(); 
	} else if(window.ActiveXObject) { 
		// Internet Explorer 5+ 
		req = new ActiveXObject("Microsoft.XMLHTTP"); 
	} else { 
		// old browser is being used. 
		alert('Problem creating the XMLHttpRequest object, You need to update your browser'); 
	} 
	//return the XMLHttpRequest object
	return req; 
} 
/////////////////////////////////////////////////////////////////////////////////////
//used to print the playlists name and the messages into the popup note 
var popup_table = '';


function printOut( name,id,sid,i,type ) {
name = (name.length > 6 )?name.substr(0,6)+'...':name;
    var oDiv = document.getElementById("note");

    var open_table  = '<table id="pl_table" width="100%" height="100%" border="0" cellpadding="2" cellspacing="0" 																																																							 						bordercolor="#000000" bgcolor="e4e4e4"><tr>';
	var close_table = '</tr></table>';
	var content="<a title=\"Add song to this playlist\" href=\"javascript:void(0);\" onClick=\"addToPlaylist("+ id +","+ sid +",'"+ 														 				type +"');refreshPlayer("+ id +");\" class=\"playlistname\">&nbsp;"+ name  +"</a>" + "</span>";

    counter = i;
	i++;
    if (!(i % 2)) {
    	popup_table += "<td width=\"125\" onMouseOver=\"rowcolor(this, '#CCCCCC')\" onMouseOut=\"rowcolor(this, '')\">&nbsp;<span              style=\"color:#000000; font-size:11px;font-weight:bold\">"+ counter +".</span>"+ content +"</td>";   
	} else {
        popup_table += "<td width=\"125\" onMouseOver=\"rowcolor(this, '#CCCCCC')\" onMouseOut=\"rowcolor(this, '')\">&nbsp;<span               style=\"color:#000000; font-size:11px;font-weight:bold\">"+ counter +".</span>"+ content +"</td></tr><tr>";
    }
	
	oDiv.innerHTML = open_table + popup_table + close_table;
	
}
/////////////////////////////////////////////////////////////////////////////////////
//used if the request for playlist return 100 that mean the user nt login so print msg that he have to login  
function printLogout( ) {
    var oDiv = document.getElementById("note"); 
	
	loginUrl= "/en/signin.php?return_url="+ encodeURIComponent(location.href);
	
    oDiv.innerHTML = "<span class=\"userinfo\">You need to logged in to add this song to playlist, if you have an Al Bawaba account, 				 					please <a href=\""+ loginUrl +"\" class=\"userinfolink\">login</a>. Otherwise, please <a                    href=\"/en/register.php\" class=\"userinfolink\">register</a> to proceed</span>. ";          
	
} 
	
/////////popup DIV/////////
	var ie = false;
	var lastNote = '';
	if (document.all) { ie = true; }


function showNote(name,sid,event,type) {  
    
	var object = document.getElementById( name );
    object.style.display = '';
	
	//the popup might be already open, in this case, we need to set its opacity to zero
	//so that when we fade it in, it looks proper
	if( 0 != object.style.opacity ){
		changeOpac(0, name);
	}
	

   //call getPlaylist function
   getPlaylists(sid,type);

	//set position for the popup note
    setPosition(event);
   
   //call the opacity function to add fade in animation through the popup note show
   opacity(name, 0, 100, 500);
   
	
} 
function rowcolor(obj, rowcolor) { //v1.1 by Project VII
	obj.style.backgroundColor=rowcolor;
}

//////////////////////////////////////////////////////////////////////////
function hideNote(name) {
    var object = document.getElementById( name ).style;


	//call the opacity function to add fad in animation through the popup note hide
    opacity(name, 100, 0, 500);
	
	
	//change the display of the div to 'none'
    object.display = 'none';
	
} 

//////////////////////////////////////////////////////////////////////////
//used to set new position for the popup note depend on the mouse event 
function setPosition(event){
    
    x = event.clientX + document.body.scrollLeft;
    y = event.clientY + document.body.scrollTop;
  	notAllowedXPosition = (event.clientX + 250);
	notAllowedYPosition = window.screen.height - (event.clientY + 370);
	
	if ( notAllowedXPosition <= 790 ){
   	 	document.getElementById('add_song_playlist').style.left = x + 'px';
    
	} else {
		document.getElementById('add_song_playlist').style.left = x - (205) + 'px';
	}
	
	if( notAllowedYPosition > 0){
		document.getElementById('add_song_playlist').style.top = y + 'px';
	} else {
		document.getElementById('add_song_playlist').style.top = y - 110 +'px';
	}	
} 

///////////////Start Fade////////////
//used to add fad in  and fad out animation on the popup note
function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;
    
    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
		
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
		
     } else if(opacStart < opacEnd) {
		 
		for(i = opacStart; i <= opacEnd; i++){
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
		
    }
	
}
/////////////////////////////////////////
//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 
/////////////////////////////////////////
function shiftOpacity(id, millisec) {
    //if an element is invisible, make it visible, else make it ivisible
    if(document.getElementById(id).style.opacity == 0) {
        opacity(id, 0, 100, millisec);
	} else {
        opacity(id, 100, 0, millisec);
    }
}
//////////End Fade///////////////////////


//////////Popup Note Timer//////////////
var secs;
var timerID = null;
var timerRunning = false;
var delay = 1000;

function InitializeTimer()
{
    // Set the length of the timer, in seconds
    secs = 1;
    StopTheClock();
    StartTheTimer();
} 

////////////////////////////////////
function StopTheClock()
{
    if(timerRunning){
        clearTimeout(timerID);
	}		
    timerRunning = false;
}
////////////////////////////////////
function StartTheTimer(){
    if (secs==0){
        StopTheClock();
        
        if(document.getElementById('add_song_playlist').style.opacity != 0){
	        hideNote('add_song_playlist');
		}
    } else {
        
        secs = secs - 1;
        timerRunning = true;
        timerID = self.setTimeout("StartTheTimer()", delay);
    }
}
////////////////////////////////////


function escCheck(e){

   var KeyID = (window.event) ? event.keyCode : e.keyCode;

	if( KeyID == 27 ){
		 if(document.getElementById('add_song_playlist').style.opacity != 0){
			 hideNote('add_song_playlist');
		 }
	window.setTimeout('document.getElementById(\'add_song_playlist\').style.top = \'-200px\';document.getElementById(\'add_song_playlist\').style.left = \'-200px\';',550);
	
	}
	
	
}


function as_hide_escKey(e){

   var KeyID = (window.event) ? event.keyCode : e.keyCode;

	if( KeyID == 27 ){
	
		 if(document.getElementById('search-results').style.display == 'block'){
			document.getElementById('search-results').style.display = 'none';
		 }
	
	}
	
	
}
function as_hide_onmousedown(e){
   var KeyID = (window.event) ? event.keyCode : e.keyCode;

		 if(document.getElementById('search-results').style.display == 'block')
			document.getElementById('search-results').style.display = 'none';
	
}
function addPlaylistDiv(){
    
    var ni = document.getElementById('body_tag');
	var content='<div style="border-width:2px; border-color:#999999;border-style:solid;"><table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0"><tr><td height="35" align="center" class="myplaylists"><img src="../images/pl.gif"  hspace="4" align="absmiddle" />My Playlists</td></tr><tr><td><div id="note" style="padding:2px" ></div></td></tr><tr bgcolor="#BABABA"><td height="10" align="right"><img src="../images/close-1.gif"  border="0" align="middle" onClick="hideNote(\'add_song_playlist\');" onMouseOver="javascript: this.src=\'../images/close-2.gif\';" onMouseOut="javascript: this.src=\'../images/close-1.gif\';"></td></tr></table></div>';
    
	var newdiv = document.createElement('div');
    
    newdiv.setAttribute("id","add_song_playlist");
    
    var browserName=navigator.appName;
    
    if ( "Netscape" == browserName){
        newdiv.setAttribute("class","notebody");
       
    }else {
        if (browserName=="Microsoft Internet Explorer"){
        	newdiv.setAttribute("className", "notebody");
		}
    }
    
    newdiv.innerHTML = content;
    ni.appendChild(newdiv);
	
	document.onkeyup = escCheck;
}
//////////////End Popup Note Timer//////////////
function refreshPlayer(plsid){
    if(popupWin && !popupWin.closed){
        popupWin.addSong(plsid);
    }
}

function changeItemStyle(me, bgColor, fgColor, level){
	if (bgColor)
		me.style.backgroundColor = bgColor;
	if (fgColor)
		me.style.color = fgColor;
}

function openWin(url,name,param){
			newWin = window.open(url,name,param);
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
/////////////////////////////////////////////////////////phase 3 //////////////////////////////////////////////////////////////////
//////////////// resend activation code///////////
function resendActivationCode(download_id){
    var xmlhttp = createRequestObject();

    
	//set the URl the will use the GET method
 	var path= "../services/popup/resend_activation.php?download_id="+download_id;
	
	//set the URl that will use the GET method to get the playlist from the server
    xmlhttp.open("GET",path,true);
    
	// check the state of request if its ready state(=4) and not url not found(=404)
    xmlhttp.onreadystatechange=	function() {
        if (xmlhttp.readyState==4) {
            if (xmlhttp.status!=404) {
				
				// create from type object
                var local = new Object();
				
				//save the returned array from the server  
              returnMsg=new Function("return " + xmlhttp.responseText)();
             
			  document.getElementById('dw_msg').style.display = '';
			  document.getElementById("dw_msg").innerHTML = returnMsg;
		//	  document.getElementById("note").innerHTML = '<span class="userinfo">' + returnMsg['message'] + '</span>';
				//print the return message in the note that song added or not
           //     document.getElementById("note").innerHTML = '<span class="userinfo">' + returnMsg['message'] + '</span>';
                
				//run the timer after finish the time period the note will disappear
         //       InitializeTimer();
                
       		} else {
				//if there an error like the link not found alert will be run for the user 
            	alert("Error,please try again");
	  		}
			
        }
    };
    xmlhttp.send(null);
}
function download_msg_Timer()
{
    // Set the length of the timer, in seconds
    secs = 1;
    StopTheClock();
    StartTheTimer();
} 