var baseUrl = 'http://www.gallomusicpublishers.co.za/index.php/';
var baseFileUrl = 'http://www.gallomusicpublishers.co.za/';

var timerGlobal = '';
var timerSearch = '';

var songsGenreSecondary = '#';

$(document).ready(function() {
	if (jQuery().lightBox) {
		$('.gallery a').lightBox({
			imageLoading:		baseFileUrl + 'application/javascript/jquery-lightbox-0.5/images/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:		baseFileUrl + 'application/javascript/jquery-lightbox-0.5/images/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:		baseFileUrl + 'application/javascript/jquery-lightbox-0.5/images/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
			imageBtnClose:	baseFileUrl + 'application/javascript/jquery-lightbox-0.5/images/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
			imageBlank:			baseFileUrl + 'application/javascript/jquery-lightbox-0.5/images/lightbox-blank.gif'
		});
	}
});


function addArtistGalleryImageUploader() {
	var $uploaderTemplate = $('form#main_form').find('div#artist_gallery_image_upload_template');
	var $uploaders = $('form#main_form').find('input[name^="artist_gallery_images"]');
	var $uploaded  = $('form#main_form').find('ul#artistImageGalleryFiles');
	var imageCount = $uploaders.length + $uploaded.find('li').length;
	
	if (imageCount < 9) {
		$('div#artist_gallery_image_upload_wrapper').append($uploaderTemplate.html());
	} else {
		alert('Only 9 images per artist');
	}
}

function deleteArtistGalleryImage(artistSlug, imageFile, listItem) {
	$.post(baseUrl+'ajax/deleteArtistGalleryImage', {'artistSlug':artistSlug,'imageFile':imageFile}, function(data) {
		if (data == 'true') {
			$(listItem).remove();
			
		}
	});
}



function sendJSONRequest(requestAction, requestData, requestTarget)
{
  requestData = JSON.stringify(requestData);
  
  $.post(baseUrl + "ajax/", { action: requestAction,
                                data: requestData },
         function(data) { requestTarget(data) }, 'json');
}



function requestUsage(songId)
{
  var requestData = Object();
  
  eval("requestData.songId = '" + songId + "'");
  
  var requestTarget = function(data)
                      {
                        if (data.result == 'requested')
                        {
                          $('span#requestUsage' + data.songId).html("<a href='javascript:requestUsage(\"" + data.songId + "\")'><img class='player_button' src='" + baseFileUrl + "application/images/cancel_request_button.png' alt='' id=''></a>");
                          
                          //show either the "Register" or "Submit" button depending on whether the user is logged in:
                          if (data.loggedIn == 0)
                          {
                            $('span#requestUsage' + data.songId).append("<a href='" + baseUrl + "musicuser/login'><img class='player_button' src='" + baseFileUrl + "application/images/player_login_button.png' alt='' id=''></a>");
                          }
                          else
                          {
                            $('span#requestUsage' + data.songId).append("<a href='" + baseUrl + "musicuser/requests/submit'><img class='player_button' src='" + baseFileUrl + "application/images/submit_song_button.png' alt='' id=''></a>");
                          }
                          
                          //increment the count in the header:
                          var requestedSongsCount = parseInt($('#requestedSongsCount').html());
                          requestedSongsCount++;
                          $('#requestedSongsCount').html(requestedSongsCount);
                          
                          $.jGrowl("The song you requested has been saved.");
                        }
                        else if (data.result == 'cancelled')
                        {
                          $('span#requestUsage' + data.songId).html("<a href='javascript:requestUsage(\"" + data.songId + "\")'><img class='player_button' src='" + baseFileUrl + "application/images/request_song_button.png' alt='' id=''></a>");
                          
                          //decrement the count in the header:
                          var requestedSongsCount = parseInt($('#requestedSongsCount').html());
                          requestedSongsCount--;
                          $('#requestedSongsCount').html(requestedSongsCount);
                          
                          $.jGrowl("The requested song has been cancelled.");
                        }
                      }
  
  sendJSONRequest('requestUsage', requestData, requestTarget);
}



/*function mp3Listen(fullSlug, songName, artistName)
{
  $mp3PlayerDisplay = $('div#mp3PlayerInfo').css('display');
  
  $('div#mp3PlayerInfo').show();
  $('span#mp3PlayerSongName').html(songName);
  $('span#mp3PlayerArtistName').html(artistName);
  
  //the Flash MP3 player needs to initialize before methods can be called for the first time,
  //so if it's just been made visible there will be a slight delay before the music starts playing:
  if ($mp3PlayerDisplay == 'none')
  {
    setTimeout("document.getElementById('mp3Player').SetVariable('player:jsUrl', '" + baseFileUrl + "application/music/" + fullSlug + "');", 4500);
    setTimeout("document.getElementById('mp3Player').SetVariable('player:jsPlay', '');", 4700);
  }
  else
  {
    document.getElementById("mp3Player").SetVariable("player:jsStop", "");
    document.getElementById('mp3Player').SetVariable('player:jsUrl', baseFileUrl + 'application/music/' + fullSlug);
    document.getElementById('mp3Player').SetVariable('player:jsPlay', '');
  }
}*/




function initializeAjaxSearch()
{
  $("input[name='search_for']").keypress(function() {
    clearTimeout(timerSearch);
    timerSearch = setTimeout("showAjaxSearch();", 1000);
  });
}

function showAjaxSearch()
{
  var requestData = Object();
    
  eval("requestData.searchTerm = '" + $("input[name='search_for']").val() + "'");
  
  var requestTarget = function(data)
                      {
                        $("#ajaxSearch").html('');
                        
                        if (data.length > 0)
                        {
                          var searchSuggestions = "<div class='green' id='suggestion_title'>Suggestions:</div><ul>";
                          
                          for (suggestion in data)
                          {
                            searchSuggestions += "<li>" + eval("data[" + suggestion + "]") + "</li>";
                          }
                          
                          searchSuggestions += '</ul>';
                          
                          $("#ajaxSearch").html(searchSuggestions);
                          
                          $("#ajaxSearch").show();
                          
                          clearTimeout(timerSearch);
                          timerSearch = setTimeout("hideAjaxSearch();", 10000);
                          
                          $("#ajaxSearch li").click(function() {
                            $("input[name='search_for']").val($(this).html());
                            $("#top_search").submit();
                          });
                        }
                        else
                        {
                          hideAjaxSearch();
                        }
                      }
  
  sendJSONRequest('searchSuggestions', requestData, requestTarget);
}

function hideAjaxSearch()
{
  $("#ajaxSearch").hide();
}




function showRequestDetails(requestId)
{
  var modalWindow = {
    parent:"body",
    windowId:null,
    content:null,
    width:null,
    height:null,
    close:function()
    {
        $(".modal_window").remove();
        $(".modal_window_overlay").remove();
    },
    open:function()
    {
        var modal = "";
        modal += "<div class=\"modal_window_overlay\"></div>";
        modal += "<div id=\"" + this.windowId + "\" class=\"modal_window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
        modal += this.content;
        modal += "</div>";    

        $(this.parent).append(modal);

        $(".modal_window").append('<input type="button" class="close_modal" id="close_modal" value="CLOSE">');
        $("#close_modal").click(function(){modalWindow.close();});
        $(".modal_window_overlay").click(function(){modalWindow.close();});
    }
  };
  
  var source = baseUrl + 'musicuser/requests/modal_review/' + requestId;
  
  modalWindow.windowId = "myModal";
  modalWindow.width = 400;
  modalWindow.height = 450;
  modalWindow.content = "<iframe width='400' height='450' frameborder='0' scrolling='auto' allowtransparency='true' src='" + source + "'></iframe>";
  modalWindow.open();
}




function publicSearchSetSecondaryTertiaryGenres(submitForm)
{
  //remove all options from secondary and tertiary genre select boxes:
  $("#songs_genre_secondary").removeOption(/./);
  
  var secondaryGenre = 0;
  
  switch ($('#songs_genre_primary :selected').text())
  {
    case 'African':      var myOptions = {
                           "#": "All",
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional"/*,
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"*/
                         }
                         secondaryGenre = 1;
                         break;
    case 'Afrikaans':    var myOptions = {
                           "#": "All"/*,
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"*/
                         }
                         secondaryGenre = 0;
                         break;
    case 'English':      var myOptions = {
                           "#": "All",
                           /*"dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",*/
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"
                         }
                         secondaryGenre = 1;
                         break;
    case 'Instrumental': var myOptions = {
                           "#": "All",
                           /*"dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",*/
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul"/*,
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"*/
                         }
                         secondaryGenre = 1;
                         break;
    case 'Reggae':       var myOptions = {
                           "#": "All"/*,
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"*/
                         }
                         secondaryGenre = 0;
                         break;
    case 'Gospel':       var myOptions = {
                           "#": "All"/*,
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"*/
                         }
                         secondaryGenre = 0;
                         break;
    default:             var myOptions = {
                           "#": "None"
                         }
                         secondaryGenre = 0;
  }
  
  if (secondaryGenre == 0)
  {
    //hide the secondary genre dropbox:
    $("#songs_genre_secondary").css("display", "none");
    $("#top_search").css("width", "410px");
  }
  else if (secondaryGenre == 1)
  {
    //display the secondary genre dropbox:
    $("#top_search").css("width", "570px");
    $("#songs_genre_secondary").css("display", "block");
  }
  
  $("#songs_genre_secondary").addOption(myOptions, false);
  
  if ($("#songs_genre_secondary").length > 0)
  {
    $("#songs_genre_secondary").val(songsGenreSecondary);
  }
  
  if (submitForm == '1')
  {
    $('#top_search').submit();
  }
}




/* Start Admin Section JSON Calls */
//var pageNumber = ""; 
//var orderBy = ""; 
	
function adminArtistsSort(pageNumber, orderBy, action)
{
  var requestData = Object();
   
   eval("requestData.pageNumber = '" + pageNumber + "'");
   eval("requestData.orderBy = '" + orderBy + "'");
   eval("requestData.action = '" + action + "'");
  
  var requestTarget = function(data)
                      {
                       
	                   
	                    var rowCounter = 0;
                        var cellFields = Array('artist_name',  'songs_count', 'date_entered');
                        var cellCounter = 0;
                     
                         // build the current heading title.s
                         $('.list_row_title').each(function() {
                        	var title_heading = $('a', this).attr("rel");
                        	 
                        	if ( title_heading == orderBy )  
                        	{ 
                        		 $('a', this).attr('id', 'current'); 
                        	} else { 
                        		 $('a', this).attr('id', ''); 
                        	}
                        	
                         });
                        
                         
                        // build the table results; 
                        $('div.list_row_wrapper').each(function() {
                          
                          $('a', this).attr('href', baseUrl + 'admin/artists/edit/' + eval("data[" + rowCounter + "].artist_slug"));
                          $('div.list_row_value', this).each(function() {
                        	  if ( cellCounter == 0 && action == 'delete' ) 
                              { 
                        		  
                             	 //alert(eval("data[" + rowCounter + "].artist_id"));
                             	 $(this).html('<input type="checkbox"  class="checkbox" id="'+eval("data[" + rowCounter + "].artist_id")+'" name="check_value[]" rel="'+eval("data[" + rowCounter + "].artist_name")+'" title="songs_'+eval("data[" + rowCounter + "].songs_count")+'">'+ eval("data[" + rowCounter + "]." + cellFields[cellCounter])); 
                              } 
                              else 
                              { 
                             	$(this).html(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                              }  
                            
                            //  alert(eval("data[" + rowCounter + "].artist_id"));
                            //alert('Row: ' + rowCounter + ', Cell: ' + cellCounter);
                            //alert(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                            cellCounter++;
                          });
                          
                          rowCounter++;
                          cellCounter = 0;
                        });
                        
                        
                      }
  
  sendJSONRequest('adminArtistsSort', requestData, requestTarget);
}



function adminSongsSort(pageNumber, orderBy, action)
{
  var requestData = Object();
    
   
   eval("requestData.pageNumber = '" + pageNumber + "'");
   eval("requestData.orderBy = '" + orderBy + "'");
   eval("requestData.action = '" + action + "'");
  
  var requestTarget = function(data)
                      {
                       
	                   // alert(action); 
	                   
	                    var rowCounter = 0;
                        var cellFields = Array('song_name',  'artist_name', 'song_genres', 'record_company_name', 'times_requested', 'song_status');
                        var cellCounter = 0;
                     
                         // build the current heading title.s
                         $('.list_row_title').each(function() {
                        	var title_heading = $('a', this).attr("rel");
                        	 
                        	if ( title_heading == orderBy )  
                        	{ 
                        		 $('a', this).attr('id', 'current'); 
                        	} else { 
                        		 $('a', this).attr('id', ''); 
                        	}
                        	
                         });
                        
                        // build the table results; 
                        $('div.list_row_wrapper').each(function() {
                          
                          $('a', this).attr('href', baseUrl + 'admin/songs/edit/' + eval("data[" + rowCounter + "].song_slug"));
                          $('div.list_row_value', this).each(function() {
                             if ( cellCounter == 0 && action == 'delete' ) 
                             { 
                            	 //alert(eval("data[" + rowCounter + "].song_id"));
                            	 $(this).html('<input type="checkbox"  class="checkbox" id="'+eval("data[" + rowCounter + "].song_id")+'" name="check_value[]" value="'+eval("data[" + rowCounter + "].song_id")+'" rel="'+eval("data[" + rowCounter + "].song_name")+'" title="songs_0">'+ eval("data[" + rowCounter + "]." + cellFields[cellCounter])); 
                             } 
                             else 
                             { 
                            	$(this).html(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                             }
                        	
                        	 
                            cellCounter++;
                          });
                          
                          rowCounter++;
                          cellCounter = 0;
                        });
                        
                        
                      }
  
  sendJSONRequest('adminSongsSort', requestData, requestTarget);
}



function autoCompleteArtist(textInput)
{
  var requestData = Object();
  eval("requestData.textInput = '" + textInput + "'");
  var requestTarget = function(data)
                      {
                        //var rowCounter = 0;
                         var optionsLength =  $('#artist_name').find('option').length; 
                        //remove all options 
                         $("#artist_name").removeOption(/./);
                         $("#artist_name").addOption("#", "Select Artist Name");
                         
                        
                        // alert( data.count_artist );
                         
	                	 if (data.count_artist > 0 ) 
	                     { 
	                		 for ( var i= 0; i < data.count_artist; i++ ) 
	                		 { 
	                			// adding an option but dont select it : false parameter 
	                			$("#artist_name").addOption(data[i].artist_id, data[i].artist_name, false);
                 		
	                		 } 
	                   
	                     }
                      }
  
   sendJSONRequest('autoCompleteArtist', requestData, requestTarget);
 
}



function adminRequestSort(pageNumber, orderBy, status)
{
  var requestData = Object();
    
   
   
   eval("requestData.pageNumber = '" + pageNumber + "'");
   eval("requestData.orderBy = '" + orderBy + "'");
   eval("requestData.status = '" + status + "'");
  
  var requestTarget = function(data)
                      {
                        
	                  

                       
                        if (status ==  'new')  
                        { 
                        	
                        	 var rowCounter = 0;
                             var cellFields = Array('project_name', 'client_name', 'song_name', 'date_requested');
                             var cellCounter = 0;
                             
                        	// build the current heading titles
                            $('#new').each(function() { 
                        	
                             $('.list_row_title', this).each(function() {
                                      	var title_heading = $('a', this).attr("rel");
                                      	 
                                      	if ( title_heading == orderBy )  
                                      	{ 
                                      		 $('a', this).attr('id', 'current'); 
                                      	} else { 
                                      		 $('a', this).attr('id', ''); 
                                      	}
                                      	
                             });
                             
                             
                             // build the table results;  
                             $('div.list_row_wrapper', this).each(function() {
                                
                                $('div.list_row_value', this).each(function() {
                              	   
                                   if ( cellCounter == 4) 
                                   { 
                                  	 //alert(eval("data[" + rowCounter + "].request_id"));
                                  	// $(this).html( eval("data["+rowCounter+"].request_id")); 
                                  	 //alert('<a href="'+baseUrl+'admin/requests/approve/'+eval("data["+rowCounter+"].request_id")+'"> Approved </a>');
                                  	 $(this).html('<a href="'+baseUrl+'/admin/requests/approve/'+eval("data["+rowCounter+"].request_id")+'"> Approve </a>'); 
                                   
                                   } 
                                   else if ( cellCounter == 5)
                                   {
                                  	 $(this).html('<a href="'+baseUrl+'/admin/requests/deny/'+eval("data["+rowCounter+"].request_id")+'"> Deny </a>'); 
                                   } 
                                   else 
                                   { 
                                  	 //alert(eval("data[" + rowCounter + "].project_name"));
                                  	$(this).html(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                                   }
                              	
                              	 
                                  cellCounter++;
                                });
                                
                                rowCounter++;
                                cellCounter = 0;
                              });
                        	
                            });
                        	
                        	
                        }
                        else if (status == 'approved')
                        { 
                        	
                        	 var rowCounter = 0;
                             var cellFields = Array('project_name', 'client_name', 'song_name', 'date_requested', 'expiry_date');
                             var cellCounter = 0;
                        	
                        	// build the current heading titles
                          $('#approved').each(function() { 
                        	
                             $('.list_row_title', this).each(function() {
                                      	var title_heading = $('a', this).attr("rel");
                                      	 
                                      	if ( title_heading == orderBy )  
                                      	{ 
                                      		 $('a', this).attr('id', 'current'); 
                                      	} else { 
                                      		 $('a', this).attr('id', ''); 
                                      	}
                                      	
                             });
                        	
                        	   $('div.list_row_wrapper', this).each(function() {
                                	 // build the current heading titles
                             
                                
                                $('div.list_row_value', this).each(function() {
                              	 // alert(cellCounter); 
                                   if ( cellCounter == 5) 
                                   { 
                                	 $(this).html('<a href="'+baseUrl+'/admin/requests/edit/'+eval("data["+rowCounter+"].request_id")+'"> Edit </a>'); 
                                   }
                                   else 
                                   { 
                                  	 //alert(eval("data[" + rowCounter + "].project_name"));
                                  	 $(this).html(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                                   }
                              	
                              	 
                                  cellCounter++;
                                });
                                
                                rowCounter++;
                                cellCounter = 0;
                              });
                        	   
                            }); 
                          
                        }
                        else if (status == 'disapproved')
                        { 
                        	
                        	 var rowCounter = 0;
                             var cellFields = Array('project_name', 'client_name', 'song_name', 'date_requested', 'expiry_date');
                             var cellCounter = 0;
                        	                        	  
                        	// build the current heading titles
                            $('#disapproved').each(function() { 
                        	
                              $('.list_row_title', this).each(function() {
                                      	var title_heading = $('a', this).attr("rel");
                                      	 
                                      	if ( title_heading == orderBy )  
                                      	{ 
                                      		 $('a', this).attr('id', 'current'); 
                                      	} else { 
                                      		 $('a', this).attr('id', ''); 
                                      	}
                                      	
                              });
                        	   
                               $('div.list_row_wrapper',this).each(function() {
                            	   
                            
                                $('div.list_row_value', this).each(function() {
                              	  // alert(cellCounter); 
                                   if ( cellCounter == 5) 
                                   { 
                                	   $(this).html('<a href="'+baseUrl+'/admin/requests/edit/'+eval("data["+rowCounter+"].request_id")+'"> Edit </a>'); 
                                   
                                   } 
                                   else 
                                   { 
                                  	 //alert(eval("data[" + rowCounter + "].project_name"));
                                  	$(this).html(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                                   }
                              	
                              	 
                                  cellCounter++;
                                });
                                
                                rowCounter++;
                                cellCounter = 0;
                              });
                               
                          }); 
                        	
                        }
                  
                      
                        
                        
                       
                        
                      }
  
  sendJSONRequest('adminRequestSort', requestData, requestTarget);
}



function adminMusicUsersSort(pageNumber, orderBy, action)
{
  var requestData = Object();
    
   
   eval("requestData.pageNumber = '" + pageNumber + "'");
   eval("requestData.orderBy = '" + orderBy + "'");
   eval("requestData.action = '" + action + "'");
  
  var requestTarget = function(data)
                      {
                       
	                   // alert(action); 
	                   
	                    var rowCounter = 0;
                        var cellFields = Array('contact_name', 'email_address', 'phone_office', 'company_name', 'status');
                        var cellCounter = 0;
                     
                         // build the current heading title.s
                         $('.list_row_title').each(function() {
                        	var title_heading = $('a', this).attr("rel");
                        	 
                        	if ( title_heading == orderBy )  
                        	{ 
                        		 $('a', this).attr('id', 'current'); 
                        	} else { 
                        		 $('a', this).attr('id', ''); 
                        	}
                        	
                         });
                        
                        // build the table results; 
                        $('div.list_row_wrapper').each(function() {
                          
                          $('a', this).attr('href', baseUrl + 'admin/musicusers/edit/' +eval("data[" + rowCounter + "].musicuser_id"));
                          $('div.list_row_value', this).each(function() {
                             if ( cellCounter == 0 && action == 'delete' ) 
                             { 
                            	 //alert(eval("data[" + rowCounter + "].musicuser_id"));
                            	 $(this).html('<input type="checkbox" id="'+eval("data[" + rowCounter + "].musicuser_id")+'" value="'+eval("data[" + rowCounter + "].musicuser_id")+'" class="checkbox" rel="'+eval("data[" + rowCounter + "].contact_name")+'">'+ eval("data[" + rowCounter + "]." + cellFields[cellCounter])); 
                             } 
                             else 
                             { 
                            	$(this).html(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                             }
                        	
                        	 
                            cellCounter++;
                          });
                          
                          rowCounter++;
                          cellCounter = 0;
                        });
                        
                        
                      }
  
  sendJSONRequest('adminMusicUsersSort', requestData, requestTarget);
}



function adminUsersSort(pageNumber, orderBy, action)
{
  var requestData = Object();
    
   
   eval("requestData.pageNumber = '" + pageNumber + "'");
   eval("requestData.orderBy = '" + orderBy + "'");
   eval("requestData.action = '" + action + "'");
  
  var requestTarget = function(data)
                      {
                       
	                   // alert(action); 
	                   
	                    var rowCounter = 0;
                        var cellFields = Array('contact_name', 'email_address', 'status');
                        var cellCounter = 0;
                     
                         // build the current heading title.s
                         $('.list_row_title').each(function() {
                        	var title_heading = $('a', this).attr("rel");
                        	 
                        	if ( title_heading == orderBy )  
                        	{ 
                        		 $('a', this).attr('id', 'current'); 
                        	} else { 
                        		 $('a', this).attr('id', ''); 
                        	}
                        	
                         });
                        
                        // build the table results; 
                        $('div.list_row_wrapper').each(function() {
                          
                          $('a', this).attr('href', baseUrl + 'admin/adminusers/edit/' +eval("data[" + rowCounter + "].adminuser_id"));
                          $('div.list_row_value', this).each(function() {
                             if ( cellCounter == 0 && action == 'delete' ) 
                             { 
                            	 //alert(eval("data[" + rowCounter + "].adminuser_id"));
                            	 $(this).html('<input type="checkbox" id="'+eval("data[" + rowCounter + "].adminuser_id")+'" value="'+eval("data[" + rowCounter + "].musicuser_id")+'" class="checkbox" rel="'+eval("data[" + rowCounter + "].contact_name")+'">'+ eval("data[" + rowCounter + "]." + cellFields[cellCounter])); 
                             } 
                             else 
                             { 
                            	$(this).html(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                             }
                        	
                        	 
                            cellCounter++;
                          });
                          
                          rowCounter++;
                          cellCounter = 0;
                        });
                        
                        
                      }
  
  sendJSONRequest('adminUsersSort', requestData, requestTarget);
}



function adminComposersSort(pageNumber, orderBy, action)
{
  var requestData = Object();
    
   
   eval("requestData.pageNumber = '" + pageNumber + "'");
   eval("requestData.orderBy = '" + orderBy + "'");
   eval("requestData.action = '" + action + "'");
  
  var requestTarget = function(data)
                      {
                       
	                   // alert(action); 
	                   
	                    var rowCounter = 0;
                        var cellFields = Array('composer_name', 'songs_count', 'date_entered');
                        var cellCounter = 0;
                     
                         // build the current heading title.s
                         $('.list_row_title').each(function() {
                        	var title_heading = $('a', this).attr("rel");
                        	 
                        	if ( title_heading == orderBy )  
                        	{ 
                        		 $('a', this).attr('id', 'current'); 
                        	} else { 
                        		 $('a', this).attr('id', ''); 
                        	}
                        	
                         });
                        
                       // build the table results; 
                         $('div.list_row_wrapper').each(function() {
                           
                           $('a', this).attr('href', baseUrl + 'admin/composers/edit/' + eval("data[" + rowCounter + "].composer_slug"));
                           $('div.list_row_value', this).each(function() {
                         	  if ( cellCounter == 0 && action == 'delete' ) 
                               { 
                              	 
                              	 $(this).html('<input type="checkbox"  class="checkbox" id="'+eval("data[" + rowCounter + "].composer_id")+'" name="check_value[]" rel="'+eval("data[" + rowCounter + "].composer_name")+'" title="songs_'+eval("data[" + rowCounter + "].songs_count")+'">'+ eval("data[" + rowCounter + "]." + cellFields[cellCounter])); 
                               } 
                               else 
                               { 
                              	$(this).html(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                               }  
                            
                             cellCounter++;
                           });
                           
                           rowCounter++;
                           cellCounter = 0;
                         });
                        
                        
                      }
  
  sendJSONRequest('adminComposersSort', requestData, requestTarget);
}


function adminComposersDiassociate(composerId, songId)
{
  var requestData = Object();
  var songs_count =  document.getElementById("songs_count").value;
 
    
   eval("requestData.composerId = '" + composerId + "'");
   eval("requestData.songId = '" + songId + "'");
   
   var requestTarget = function(data)
   {  
	   //remove the no song assciated row if any 
	   if (songs_count == 0) 
	   { 
		  $("#no_song_associated").remove(); 
	   }
	   $("div[id='" + data + "']").remove(); 
	 
   }

  
  sendJSONRequest('adminComposersDiassociate', requestData, requestTarget);
}



function adminComposersAssociate()
{
	var composerId=  document.getElementById("composer_id").value;
	var selectedSongId=  document.getElementById("associate_song").value;
	var songs_count =  document.getElementById("songs_count").value;
	
	if(selectedSongId == '#') 
	{ 
       $("#main_form_error").html("Please Select a song to associate").show().fadeOut(10000);
   	}
	else 
	{ 
	   var requestData = Object();
	   eval("requestData.composerId = '" + composerId + "'");
	   eval("requestData.selectedSongId = '" + selectedSongId + "'");
	   // put some qoutes 
	   compId =  "'"+composerId+"'"; 
	   songId =  "'"+selectedSongId+"'"; 
	   
	   var requestTarget = function(data)
       { 
		   
		   var rowCounter = 0;
		   //remove the no song assciated row if any 
		   if (songs_count == 0) 
		   { 
			  $("#no_song_associated").remove(); 
		   }
		   
		   $("div.list_table_wrapper").append(' <div class="list_row_wrapper" id="'+eval("data["+rowCounter+"].song_id")+'"><div class="list_row_value" id="description">'+eval("data["+rowCounter+"].song_name")+'</div><div class="list_row_value"> '+eval("data["+rowCounter+"].song_slug")+'</div> <div class="list_row_value"> '+eval("data["+rowCounter+"].date_entered")+'</div><div class="list_row_value"><a href="javascript:adminComposersDiassociate('+compId+','+songId+')"> Di-associate </a></div></div>');
		  
       }

	   sendJSONRequest('adminComposersAssociate', requestData, requestTarget);
	   
	}
	
}



function selectOnotherComposer()
{
	var selectComposerCount =  parseInt(document.getElementById("select_composer_count").value);
	
    selectComposerCount = selectComposerCount + 1; 
    	
	itemToRemove = "'select_composer_"+selectComposerCount+ "'"; 
	
	$("#additional_select_composer").append('<div id="select_composer_'+selectComposerCount+'"><select name="select_composer_'+selectComposerCount+'" ><option value="#">Select Composer</option></select> &nbsp; &nbsp; <a href="javascript:removeSelectedComposer('+itemToRemove+')"> remove </a> </div><br/>') ; 
	document.getElementById("select_composer_count").value =  selectComposerCount; 

	 // alert('setting data');
	var requestData = Object();
	 // eval("requestData.test= 'test");
	 // alert('setting target'); 
	var requestTarget = function(data)
    { 
		 //alert('target activated');
        // alert(data.count_composers);
	   var rowCounter = 0;
	 
	   if (data.count_composers > 0 ) 
       { 
  		 for ( var i= 0; i < data.count_composers; i++ ) 
  		 { 
  			   //add an option but dont select it : false parameter 
  			$("select[name='select_composer_" + selectComposerCount + "']").addOption(data[i].id, data[i].name, false);
  			
  		 } 
     
       }
	
		  
    }
	//alert('sending request');
    sendJSONRequest('selectOnotherComposer', requestData, requestTarget);
    
}



function removeSelectedComposer(item)
{ 
    //alert(item); 
	$("div[id='" + item + "']").remove();
	
}




function addAnotherComposer()
{
	var inputComposerCount =  parseInt(document.getElementById("input_composer_count").value);
	
	inputComposerCount = inputComposerCount + 1; 
	
	itemToRemove = "'input_composer_"+inputComposerCount+ "'"; 
	
	$("#additional_input_composer").append('<div id="input_composer_'+inputComposerCount+'"><input type="text" name="add_composer_'+inputComposerCount+'" value=""/> &nbsp; &nbsp; <a href="javascript:removeAddedComposer('+itemToRemove+')"> remove </a> <div><br/>') ; 
	document.getElementById("input_composer_count").value =  inputComposerCount; 
    
}

function removeAddedComposer(item)
{ 
	$("div[id='" + item + "']").remove();
	
}



function adminNewsSort(pageNumber, orderBy, action)
{
  var requestData = Object();
    
   
   eval("requestData.pageNumber = '" + pageNumber + "'");
   eval("requestData.orderBy = '" + orderBy + "'");
   eval("requestData.action = '" + action + "'");
  
  var requestTarget = function(data)
                      {
                       
	                   
	                    var rowCounter = 0;
                        var cellFields = Array('news_title',  'author_name', 'date_published', 'news_status');
                        var cellCounter = 0;
                     
                         // build the current heading title.s
                         $('.list_row_title').each(function() {
                        	var title_heading = $('a', this).attr("rel");
                        	 
                        	if ( title_heading == orderBy )  
                        	{ 
                        		 $('a', this).attr('id', 'current'); 
                        	} else { 
                        		 $('a', this).attr('id', ''); 
                        	}
                        	
                         });
                        
                        // build the table results; 
                        $('div.list_row_wrapper').each(function() {
                          
                          $('a', this).attr('href', baseUrl + 'admin/news/edit/' + eval("data[" + rowCounter + "]." + cellFields[1]));
                          $('div.list_row_value', this).each(function() {
                        	  if ( cellCounter == 0 && action == 'delete' ) 
                              { 
                             	 $(this).html('<input type="checkbox"  class="checkbox" id="'+eval("data[" + rowCounter + "].news_id")+'" name="check_value[]" rel="'+eval("data[" + rowCounter + "].news_title")+'" title="songs_'+eval("data[" + rowCounter + "].songs_count")+'">'+ eval("data[" + rowCounter + "]." + cellFields[cellCounter])); 
                              } 
                              else 
                              { 
                             	$(this).html(eval("data[" + rowCounter + "]." + cellFields[cellCounter]));
                              }  
                            cellCounter++;
                          });
                          
                          rowCounter++;
                          cellCounter = 0;
                        });
                        
                        
                      }
  
  sendJSONRequest('adminNewsSort', requestData, requestTarget);
}



function adminSongAddSetSecondaryTertiaryGenres(primaryGenreSelectBox)
{
  //remove all options from secondary and tertiary genre select boxes:
  $("#songs_genre_2").removeOption(/./);
  $("#songs_genre_3").removeOption(/./);
  
  switch ($(':selected', primaryGenreSelectBox).text())
  {
    case 'African':      var myOptions = {
                           "#": "None",
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"
                         }
                         break;
    case 'Afrikaans':    var myOptions = {
                           "#": "None",
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"
                         }
                         break;
    case 'English':      var myOptions = {
                           "#": "None",
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"
                         }
                         break;
    case 'Instrumental': var myOptions = {
                           "#": "None",
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"
                         }
                         break;
    case 'Reggae':       var myOptions = {
                           "#": "None",
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"
                         }
                         break;
    case 'Gospel':       var myOptions = {
                           "#": "None",
                           "dc05ebc9aaa3e97c21bc7698c3009ccf": "African - Acapella",
                           "8d68a2bd50bd49ceaa3d9fbb008fe5fc": "African - Afro-Jazz",
                           "f9c9fdb78c29234f0bb9a34912a739e1": "African - Afro-Soul",
                           "959755e8a5f563c3235fe528c27f6045": "African - Pop",
                           "27a56ae854b2c58821c91fe1313dc7c1": "African - Traditional",
                           "1eb1e1e98830a5e8e31a0ba3dc2279ea": "English - Pop",
                           "026543c47969177b7d3cf67780a49d51": "English - Soul"
                         }
                         break;
    default:             var myOptions = {
                           "#": "None"
                         }
  }
  
  $("#songs_genre_2").addOption(myOptions, false);
  $("#songs_genre_3").addOption(myOptions, false);
}

/*function adminRequestStatusChanged()
{
  if ($('#request_status :selected').val() == 'disapproved')
  {
    $('#denied_reason_span').css('display', 'block');
  }
  else
  {
    $('#denied_reason_span').css('display', 'none');
  }
}*/



/* End Admin Section JSON Calls */



$(document).ready(function() {

  //hide any MP3 player info blocks:
  $('div#mp3PlayerInfo').hide();
  
  //bind the onchange event for the search box at the top of the page:
  initializeAjaxSearch();
  
  //fade out page messages after the specified amount of milliseconds:
  setTimeout("$('div.pageMessages').fadeOut('slow');", 5000);
  
  //initialize search select boxes:
  publicSearchSetSecondaryTertiaryGenres('0');
  
  /* Cancel the song form request */
  $('.cancel_step').click(function() {
    self.location="../requests/submit";
  });
  
  /*  Request song form in steps */ 
  $('.next_step').click( function() {
  	  var step = $(this).attr("id"); 
  	 
  	  if (step == 'go_step2') { 
  		  var fieldSetName = 'frm_step_1'; 
		   // vaidate fields 
    	  if ( validateField(fieldSetName) == true ) 
    	  {  
    	     $('#frm_step_4').hide();
    	     $('#frm_step_3').hide();
    	     $('#frm_step_1').hide();
    	     $('#frm_step_2').toggle(400);
    	  } 
		  
  	  }
  	  else if (step == 'go_step3') { 
  		var fieldSetName = 'frm_step_2'; 
  		
  		if  ( isThereAnyMediaChecked() == true &&  isThereAnyTerritoryChecked() == true ) 
  		{ 
  			
  			 // determine terms in the step 3. 
  			$("input[name='parent_media[]']").each(function() {
  			
  			 if ( this.checked== true &&  $(this).attr("rel") == 'Advertising') 
  			 {
  				 $("#terms_advertisement").show();  
  				 $("#terms_documentary").hide();  
  				 $("#terms_feature_film").hide(); 
  				 $("#terms_multimedia_presentation").hide();
  			 }
  			 else if ( this.checked == true &&  $(this).attr("rel") == 'Feature Film')
  			 {
  				 $("#terms_advertisement").hide();  
  				 $("#terms_documentary").hide();  
  				 $("#terms_feature_film").show();
  				 $("#terms_multimedia_presentation").hide();
  			 }
  			 else if ( this.checked == true && $(this).attr("rel") == 'Documentary' ) 
  			 {
  				 $("#terms_advertisement").hide();  
  				 $("#terms_documentary").show();  
  				 $("#terms_feature_film").hide();
  				 $("#terms_multimedia_presentation").hide();
  		     }
  			 else if ( this.checked == true && $(this).attr("rel") == 'Multimedia / Presentations' ) 
 			 {
 				 $("#terms_advertisement").hide();  
 				 $("#terms_documentary").hide();  
 				 $("#terms_feature_film").hide();
 				 $("#terms_multimedia_presentation").show();
 		     }
  			 
  	       }); 
  			
  			 $('#frm_step_4').hide();
  	   	     $('#frm_step_2').hide();
  	   	     $('#frm_step_1').hide();
  	   	     $('#frm_step_3').toggle(400);	
  		
  		
  		
  		}else { 
  			 
  			 $("#main_form_error").html("Please choose at least one Media and one Territory option!").show().fadeOut(10000);
  	         window.scrollTo(0,0); 
  			
  		}
  		 
  		  
  	  } 
  	  else if (step == 'go_step4') { 
  		var fieldSetName = 'frm_step_4'; 
  		
		   // vaidate fields 
	    if (isThereAnyDurationChecked() == true  && isThereAnyUsageChecked() == true &&  isThereAnyTermsChecked() == true  ) 
	    {
	     showRecapForm();
  		 $('#frm_step_3').hide();
  	     $('#frm_step_2').hide();
  	     $('#frm_step_1').hide();
  	     $('#frm_step_4').toggle(400);
  	     
	    }else { 
	    	 $("#main_form_error").html("Please choose at least one Song Duration, one Usage, and one Terms option!").show().fadeOut(10000);
  	         window.scrollTo(0,0); 
	    }
	    
  	  }
      

	
  });
  
  
  
  //validate input fields and return true if the required ones are all validated.   
  function validateField(myForm) { 
	
	   // using this example ..  
	   // myObject = document.getElementById('frm_step1').getElementsByTagName('input');
	   // myObject = $('#frm_step1 > input');
 
	 var tBoxInput = $("fieldset[id='" + myForm + "']  > input");
	 var selectMenu = $("fieldset[id='" + myForm + "'] > select");
	 var tAreaInput = $("fieldset[id='" + myForm + "'] > textarea");
	 
	   // counter variables. 
	 var countTextbox = 0;
	 var countValidatedTBoxes = 0;

     var countTextarea = 0;
	 var countValidatedTAreas = 0;

	 var countSelect = 0;
	 var countValidatedSelects = 0
	 
	  // for all input text boxes 
	 for (var i=0; i < tBoxInput.length; i++)
  	 {
		 
		 if (tBoxInput[i].className.match("textbox") )
		 {
			 
			 if(tBoxInput[i].value == '') 
			 {
			     //is this the script upload field?
			     if (tBoxInput[i].name == 'req_synopsis')
			     {
			       if (document.getElementById('req_addi_info').value != '')
			       {
			         //the additional info field was filled in, no need for a script upload:
			         tBoxInput[i].style.border = '1px solid #ccc';
    				 countValidatedTBoxes++;
			       }
			       else
			       {
			         //the additional info field wasn't filled in, we need a script upload:
			         tBoxInput[i].style.border = '1px solid #E76757';
			       }
			     }
			     else
			     {
				   tBoxInput[i].style.border = '1px solid #E76757';
				 }
			 }
			 else
			 {
				tBoxInput[i].style.border = '1px solid #ccc';
				countValidatedTBoxes++;
			 }
			 countTextbox++;
		 }
		 
  	 }
	 
	  // for all select boxes 
	 for (var i=0; i < selectMenu.length; i++)
 	 {
 		 if (selectMenu[i].className.match("selectmenu"))
 		 { 
 			 if (tBoxInput[i].getAttribute('id') == 'reg_sub_category') {
 				 if( (selectMenu[i].value == "#") || (document.getElementById("adding_new_subcat").value == '0')) {
 						var ruturn_error_message = '5';
 						selectMenu[i].style.backgroundColor = '#E76757';
 				 }else {
 						selectMenu[i].style.backgroundColor = '#ffffff';
 						countValidatedSelects++;
 				 }
 			 }else {
                if(selectMenu[i].value == "#") {
               	selectMenu[i].style.backgroundColor = '#E76757';
				 }else{
					selectMenu[i].style.backgroundColor = '#ffffff';
					countValidatedSelects++;
			     }
			}
 			countSelect++;
 		 }
 	  }
	 
	 
	 
	  // for all textareas 
	 for (var i=0; i < tAreaInput.length; i++)
 	 {
 		 if (tAreaInput[i].className.match("textarea"))
 		 {
 			 if(tAreaInput[i].value == '')
 			 {
 			    //is this the script upload field?
			     if (tAreaInput[i].name == 'req_addi_info')
			     {
			       if (document.getElementById('req_synopsis').value != '')
			       {
			         //the additional info field was filled in, no need for a script upload:
			         tAreaInput[i].style.border = '1px solid #ccc';
    				 countValidatedTAreas++;
			       }
			       else
			       {
			         //the additional info field wasn't filled in, we need a script upload:
			         tAreaInput[i].style.border = '1px solid #E76757';
			       }
			     }
			     else
			     {
				   tAreaInput[i].style.border = '1px solid #E76757';
				 }
 			 }
			 else
			 {
                tAreaInput[i].style.border = '1px solid #ccc';
				countValidatedTAreas++;
			 }

			 countTextarea++;

 		}

 	  }
	 
		 
	  // return 
	 if((countTextbox == countValidatedTBoxes) && (countTextarea == countValidatedTAreas) && (countSelect == countValidatedSelects)) 
	 {
         return true; 
     } 
	 else 
	 { 
		 $("#main_form_error").html("Please complete all the required fields!").show().fadeOut(10000);
         window.scrollTo(0,0); 
         return false;
	 }
	 
	 
		 
		 
  } 
  
  
  $('.previous_step').click( function() {
  	  var step = $(this).attr("id"); 
  	  
  	 
      if (step == 'go_step1') { 
		 
    	  $('#frm_step_4').hide();
    	  $('#frm_step_3').hide();
    	  $('#frm_step_2').hide();
          $('#frm_step_1').toggle(400); 
      
	  }else if (step == 'go_step2') { 
  		  
		  $('#frm_step_4').hide();
    	  $('#frm_step_3').hide();
    	  $('#frm_step_1').hide();
    	  $('#frm_step_2').toggle(400);
		  
  	  }else if (step == 'go_step3') { 
  		  
  		 $('#frm_step_4').hide();
   	     $('#frm_step_2').hide();
   	     $('#frm_step_1').hide();
   	     $('#frm_step_3').toggle(400);
  		  
  	  } else if (step == 'go_step4') { 
  		
  		 $('#frm_step_3').hide();
  	     $('#frm_step_2').hide();
  	     $('#frm_step_1').hide();
  	     $('#frm_step_4').toggle(400);
  	  }
  	   
  	
	
  });
  
  
  
  
  
  $("input[name='parent_media[]']").click(function(){
	   // the code for media 
	   
	 var id_checked = $(this).attr("id").substring(13,100);
	 
  	 $("li[class='list_subtitle']").hide();
	 $("li[class='list_subtitle_open']").hide();
	 $("input[name='media[]']").each(function() {
         this.checked = false;
     });
	 
	 if (this.checked == true ) { 
		  // show all children	 
		 $("li[id='child_" + id_checked + "']").show(); 

	 }
	 

		 
  });
  
  
  
  
  $("input[type=checkbox]").click(function(){
	   // the code for media 
	 var id_checked = $(this).attr("id").substring(13,100);
	 
	 if (this.checked == true ) { 
		 // show all children	 
		 $("li[id='child_" + id_checked + "']").show(); 

	 }
	 else 
	 { 
		// uncheck childrens and hihde theme. 
		$("input[id='media_" + id_checked + "']").each(function() {
           this.checked = false;
       });
	    
		$("li[id='child_" + id_checked + "']").hide();
	     	     
	    
	 }
	 
	 
	 // the territory 
	 var territory_checked = $(this).attr("id").substring(0,10);
	 //  alert(territory_checked);  
	 if (territory_checked == 'territory_' &&  $(this).attr("rel") == 'Other' && (this.checked == true) ) { 
		 // show other territory 	
		 $("#div_other_territory").show(); 

	 } else if ( (territory_checked == 'territory_') &&  ($(this).attr("rel") == 'Other') && (this.checked == false) ) { 
		 document.getElementById('other_territory').value =   ''; 
		 $("#div_other_territory").hide(); 
	 }
	
	 
 
 });
  
  
  function isThereAnyMediaChecked() { 
	
	 var return_value =  false;
	 $("input[type=radio]").each ( function() {
		 var id_checked = $(this).attr("id").substring(13,100);
		 
		 if ( $(this).attr("id").substring(0,12) == 'parent_media' && this.checked ==  true && $(this).attr("rel") == 'Multimedia / Presentations' ) { 
			  return_value =  true; 
		 } 
		 else 
		 { 
		
		 $("input[name='media[]']").each(function(){
			 var child =  'media_'+ id_checked; 
			 if ( $(this).attr("id").substring(0,6) == 'media_' && this.checked ==  true ) { 
				  return_value =  true;
			 } 
		 }); 
		 
		 }
		
		
		 
	 }); 
	 
	 return  return_value; 
	 
	
	}
  
  
   function isThereAnyTerritoryChecked(){ 
	    
	     var return_value =  false;
	   $("input[type=checkbox]").each ( function() { 
		
		  if ($(this).attr("id").substring(0,6) == 'territ' && this.checked ==  true ) { 
				 return_value =  true; 
		  } 
		  
		  if ($(this).attr("id").substring(0,6) == 'territ'  && this.checked ==  true && $(this).attr("rel") == 'Other' &&  document.getElementById('other_territory').value == '') { 
				 document.getElementById('other_territory').style.border = '1px solid #E76757';
				 return_value = false; 
		  }

	
	   }); 
	   
	   return return_value; 
	   
   }
   
   
   
      
   
   function isThereAnyDurationChecked(){ 
	    
	     var return_value =  false;
	   $("input[name='duration[]']").each ( function() { 
		
		  if (this.checked ==  true ) { 
				 return_value =  true; 
		  } 

	   }); 
	   
	   
	   if (return_value ==  false && document.getElementById('other_duration').value == '') { 
				 document.getElementById('other_duration').style.border = '1px solid #E76757';
				 return_value = false; 
	   }else if (return_value ==  false && document.getElementById('other_duration').value != '') {  
		         document.getElementById('other_duration').style.border = '1px solid #ccc';
			     return_value = true; 
	   }
	   
	  return return_value; 
	   
  }
   
   
   function isThereAnyUsageChecked(){ 
	    
	     var return_value =  false;
	   $("input[name='usage[]']").each ( function() { 
		
		  if (this.checked ==  true ) { 
				 return_value =  true; 
		  } 

	   }); 
	   
	   
	   
	  return return_value; 
	   
   }
   
   function isThereAnyTermsChecked() { 
	    
	    var return_value =  false;
	  
	   $("input[name='parent_media[]']").each(function() {
		   
		  if ( this.checked == true && $(this).attr("rel") == 'Advertising') 
		  { 
			 
			  
			  $("input[name='terms_advertisement[]']").each ( function() { 
				  if (this.checked ==  true ) { 
						 return_value =  true; 
				  } 

			   }); 
			  
			  if (return_value ==  false && document.getElementById('other_terms_advertisement').value == '') { 
					 document.getElementById('other_terms_advertisement').style.border = '1px solid #E76757';
					 return_value = false; 
		      }else if (return_value ==  false && document.getElementById('other_terms_advertisement').value != '') {  
			         document.getElementById('other_terms_advertisement').style.border = '1px solid #ccc';
				     return_value = true; 
		      }
			  
		  }
	   
	   
	      if (this.checked == true && $(this).attr("rel") == 'Feature Film') 
		  { 
	    	  
			  $("input[name='terms_feature_film[]']").each ( function() { 
				  if (this.checked ==  true ) { 
						 return_value =  true; 
				  } 

			   });  
			  
			  if (return_value ==  false && document.getElementById('other_terms_feature_film').value == '') { 
					 document.getElementById('other_terms_feature_film').style.border = '1px solid #E76757';
					 return_value = false; 
		      }else if (return_value ==  false && document.getElementById('other_terms_feature_film').value != '') {  
			         document.getElementById('other_terms_feature_film').style.border = '1px solid #ccc';
				     return_value = true; 
		      }
			  
		  }
	      
	      if (this.checked == true && $(this).attr("rel") == 'Documentary') 
		  { 
	    	 
			  $("input[name='terms_documentary[]']").each ( function() { 
				  if (this.checked ==  true ) { 
						 return_value =  true; 
				  } 

			   });    
			  
		  }
	      
	      if (this.checked == true && $(this).attr("rel") == 'Multimedia / Presentations') 
	      { 
	    	  
	    	   return_value =  true;				  
	      }

			   
       }); 
	
	   
	  return return_value; 
	   
  }
   
   
	// for the durations 
	$("input[name=other_duration]").focus(function () { 
		   $("input[name='duration[]']").each(function() {
	        this.checked = false;
	    });
		   
	}); 
	
	$("input[name='duration[]']").click(function() {
		   document.getElementById('other_duration').value =  ''; 
		   document.getElementById('other_duration').style.border = '1px solid #ccc';
	});
	
	
	// for the addvertisment 
	   $("input[name=other_terms_advertisement]").focus(function () { 
		   $("input[name='terms_advertisement[]']").each(function() {
	           this.checked = false;
	       });
		   
	   }); 
	   
	   $("input[name='terms_advertisement[]']").click(function() {
		   document.getElementById('other_terms_advertisement').value =  ''; 
		   document.getElementById('other_terms_advertisement').style.border = '1px solid #ccc';
	   });
	   
	   
	   
	   
	 // for features film 
	   $("input[name=other_terms_feature_film]").focus(function () { 
		   $("input[name='terms_feature_film[]']").each(function() {
	           this.checked = false;
	       });
		   
	   }); 
	   
	   $("input[name='terms_feature_film[]']").click(function() {
		   document.getElementById('other_terms_feature_film').value =  ''; 
		   document.getElementById('other_terms_feature_film').style.border = '1px solid #ccc';
	   });
   
   
       // STEP 4 FORM RECAP 
	   
	   
     function showRecapForm() 
     {
         //contact details: 
         var recap_client_name = $('#req_client').val();
         $("#recap_client_name").html(recap_client_name).show();
         
         var recap_company_name = $('#req_company_name').val();
         $("#recap_company_name").html(recap_company_name).show(); 
         
         var recap_contact_name = $('#req_contact_name').val();
         $("#recap_contact_name").html(recap_contact_name).show(); 
         
         var recap_contact_email = $('#req_contact_email').val();
         $("#recap_contact_email").html(recap_contact_email).show(); 
    	 
         // project details. 
         var recap_production = $('#req_production').val();
         $("#recap_production").html(recap_production).show(); 
         
         var recap_additional_info = $('#req_addi_info').val();
         $("#recap_additional_info").html(recap_additional_info).show();
         
         var recap_script = $('#req_synopsis').val();
         
         if (recap_script != '') { 
        	 $("#recap_script").html('Yes ' + '<br/> <strong>File name :</strong> ' + recap_script ).show(); 
         }
         else 
         {
        	 $("#recap_script").html('No').show(); 
         }
         
         // media details. 
         
         $("input[name='parent_media[]']").each ( function() {
    		  
        	 if ( this.checked ==  true ) { 
    			 var parent_media = $(this).attr("rel");
    			 
    			 var child_media = ' ( '; 
    			 
        		 $("input[name='media[]']").each(function(){
        			 if ( this.checked ==  true ) { 
        				 child_media +=  $(this).attr("rel") +  ', ';  
        			 }
        		 }); 
        		     //child_media +=  ' )';
        		     child_media = child_media.substring(0, child_media.length - 2) + ' )';
        		
        		var recap_media =  parent_media +  child_media; 
        		$("#recap_media").html(recap_media).show(); 
    		 } 
    		
    		    		 
    	 });
         
         
      //  territories detials 
         var territories = ''; 
         $("input[name='territory[]']").each ( function() {
    		 if ( this.checked ==  true ) { 
        	    if ( $(this).attr("rel") == 'Other') 
        	    { 
        	    	
        	    	var territory = $(this).attr("rel") + ':'+ document.getElementById('other_territory').value; 
        	    }
        	    else 
        	    {
        	    	var territory = $(this).attr("rel")	
        	    }
    			territories +=  territory +  ', ';
        		 
    		 }  		 
    	 });
        
         territories = territories.substring(0, territories.length - 2);
         
         $("#recap_territories").html(territories).show(); 
  	 
    	 
         
     //  song duration 
           var duration = ''; 
        $("input[name='duration[]']").each ( function() {
		
    	    if ( document.getElementById('other_duration').value != '') 
    	    { 
    	    	 duration = document.getElementById('other_duration').value; 
    	    }
    	    else if ( this.checked ==  true )
    	    {
    	    	 duration = $(this).attr("value"); 
    	    }    		 
		   		 
	    });
        $("#recap_duration").html(duration).show();  
        
        
        //  song usage 
        var usage = ''; 
       $("input[name='usage[]']").each ( function() {
    	   if ( this.checked ==  true )
    	   {
 	    	 usage = $(this).attr("value"); 
    	   }    		 
		   		 
	   });
        $("#recap_usage").html(usage).show();  
        
        
        
        // song terms 
        
        
        var terms = ''; 
        $("input[name='parent_media[]']").each(function() {
            
        	
        	 if ( this.checked == true && $(this).attr("rel") == 'Advertising') 
   		     { 
   			  
        		       $("input[name='terms_advertisement[]']").each ( function() { 
        				
        	    	    if ( document.getElementById('other_terms_advertisement').value != '') 
        	    	    { 
        	    	    	terms = document.getElementById('other_terms_advertisement').value; 
        	    	    }
        	    	    else if ( this.checked ==  true )
        	    	    {
        	    	    	 terms  = $(this).attr("value"); 
        	    	    }    		 
        	        });
   			  
   			 }
        	 
        	 
        	 if ( this.checked == true && $(this).attr("rel") == 'Feature Film') 
   		     { 
   			  
        		       $("input[name='terms_feature_film[]']").each ( function() { 
        				
        	    	    if ( document.getElementById('other_terms_feature_film').value != '') 
        	    	    { 
        	    	    	terms = document.getElementById('other_terms_feature_film').value; 
        	    	    }
        	    	    else if ( this.checked ==  true )
        	    	    {
        	    	    	 terms  = $(this).attr("value"); 
        	    	    }    		 
        	        });
   			  
   			 }
        	 
        	 if ( this.checked == true && $(this).attr("rel") == 'Documentary') 
   		     { 
   			  
        		    $("input[name='terms_documentary[]']").each ( function() { 
        				if ( this.checked ==  true )
        	    	    {
        	    	    	 terms  = $(this).attr("value"); 
        	    	    }    		 
        	        });
   			  
   			 }
        	 
        	 if ( this.checked == true && $(this).attr("rel") == 'Multimedia / Presentations') 
   		     { 
   			  
                    terms  = 'None'; 
        	    	
   			 }
        	
        	
        	
        	
	    });
        
        $("#recap_terms").html(terms).show();  
        
        
        
        
	 
	 
    }
     
     
     

     function capitaliseFirstLetter(str)
     {
     	 //check that str is a string
     	if(typeof str != String)
     	{
     		alert( "it is not a string"); 
     		return str;
     	
     	}
     	//extract the first letter of str
     	var letter = str.substr(0,1);
     	//return letter capitalised concatonated with
     	//str minus it's first letter
     	return letter.toUpperCase() + str.substr(1);
     }
     
     
     $('#other_territory').blur(function() { 
    	// territory_value = document.getElementById('other_territory').value; 
    	 
    	 //alert(  capitaliseFirstLetter( territory_value.toString() )) ; 
     })
     
     
  

   /*  End Request song form in steps */ 
     
     
     
     
     
     
     
     /* ---------------------  ADMINISTRATION SIDE START HERE   ------------------------------------------*/ 
     
     $('#cancel_button').click( function() {
         url_to_use = $(this).attr('rel');
         window.location=url_to_use;
     });
     
     
     /* start delete listed table values function  */ 
     $('#form_delete').submit( function(e) {
         e.preventDefault();
        var link = document.getElementById('form_delete').getAttribute('action');
        var name_to_delete = '<ul>';
        j=document.getElementById('form_delete').max_num_per_page.value;
         var checked_items = 0;

        if ( j == 1 ) {
            if (document.form_delete["check_value[]"].checked )  {
            	 var assotiatedItems = document.form_delete["check_value[]"].getAttribute('title'); 
            	 var arrayAssotiatedItems = assotiatedItems.split('_'); 
            	if (arrayAssotiatedItems[1] > 0) 
                { 
              	  associatedItems = '&nbsp;<font color="red"> '+ arrayAssotiatedItems[1] + ' ' + arrayAssotiatedItems[0] + ' associated will also be deleted</font>'; 
                } else { 
              	  associatedItems = ''; 
                } 
            	
            	name_to_delete += '<li>' + document.form_delete["check_value[]"].getAttribute('rel') + '</li>';
            	
               checked_items = 1;
             }
        } else {

         for (i=0; i<j; i++){

                if (document.form_delete["check_value[]"][i].checked) {
                	 var assotiatedItems = document.form_delete["check_value[]"][i].getAttribute('title'); 
                	 var arrayAssotiatedItems = assotiatedItems.split('_'); 
                	
                      if (arrayAssotiatedItems[1] > 0) 
                      { 
                    	  associatedItems = '&nbsp;<font color="red"> '+ arrayAssotiatedItems[1] + ' ' + arrayAssotiatedItems[0] + ' associated will also be deleted</font>'; 
                      } else { 
                    	  associatedItems = ''; 
                      } 
                      
		               document.form_delete["check_value[]"][i].value;  // a id to remove
		               name_to_delete += '<li>' + document.form_delete["check_value[]"][i].getAttribute('rel') + ' '+ associatedItems + '</li>';
                       checked_items = 1;
		         }
	      }

	      }


            name_to_delete = name_to_delete + '</ul>';

        if (checked_items == 0) {
          var message_display =  " Please check at least one item";
          dialog_box( message_display, function () {
		   });
        } else {
	       var message_display =  "Are you sure you want to delete ? <b>" + name_to_delete + "</b> ";
          confirm( message_display, function () {
		   	// window.location.href = link; // if you want to submit an individual item
		 	  document.form_delete.submit();  // this is used to submit values of a form
	 	 });

	 	 }

    });
     
     function confirm(message, callback) {
    	 $('#confirm').modal({
    		 close:false,
    		 overlayId:'confirmModalOverlay',
    		 containerId:'confirmModalContainer',
    		 onShow: function (dialog) {
    	     dialog.data.find('.message').append(message);

    	     // if the user clicks "yes"
    			dialog.data.find('.yes').click(function () {
    				// call the callback
    				if ($.isFunction(callback)) {
    					 callback.apply();
    					//return true;
    				}
    				// close the dialog

    				$.modal.close();
    			});

    		}
    	});
     }





      function dialog_box(message, callback) {
    	 $('#dalog_box').modal({
    		 close:false,
    		 overlayId:'confirmModalOverlay',
    		 containerId:'confirmModalContainer',
    		 onShow: function (dialog) {
    	     dialog.data.find('.message').append(message);

    	     // if the user clicks "yes"
    			dialog.data.find('.close').click(function () {
    				// close the dialog
    				 $.modal.close();
    			});

    		}
    	});
       }
      
     /* end delete listed table values function  */ 
      
      
      /* complete select boxes automaticaly */ 
      
      $('#select_suggest').keyup(function(){
         
    	   clearTimeout(timerGlobal);
    	   //timerGlobal = self.setTimeout("alert('test');", 2000);
    	 
    	   timerGlobal = setTimeout("autoCompleteArtist(document.getElementById('select_suggest').value);", 2000);
      }); 
      
      
    //DATE PICKER
      $(document).ready(function() {
      	$('.date-pick').datePicker({startDate:'1910-01-01'});
      	$('.date-pick-not-validated').datePicker({startDate:'1910-01-01'});
      });
      
      
      
      $("#new_expiry_date").blur(function() {
          // claim date validation.  
    	 var valid_date = true; 
    	 var date = $("#new_expiry_date").val();
    	 var input_date =  document.getElementById("new_expiry_date");
    	 
    	 date_year =  date.substring(0,4);
    	 date_month = date.substring(5,7);
    	 date_day =   date.substring(8,10);
    	 
    		
    	
       if (isNumeric(date_year) == false ||  date_year.length != 4 ) {
            valid_date = false; 
       }else if ( isNumeric(date_month) == false ||  date_month.length != 2  || check_month_count(date_month) == false ) { 
    	   valid_date = false;
       }else if ( isNumeric(date_day) == false ||  date_day.length != 2  || check_days_count(date_day, date_month) == false ) { 
    	   valid_date = false;
       } else { 
    	   valid_date = true;
       }
       
       
       if (valid_date == false ) { 
    	   
    	   $("#valid_date_error").html("Valid date format is YYYY-MM-DD for eg. 2009-03-27").show().fadeOut(7000);
    	   input_date.style.border = '1px solid #E76757';
       }else { 
    	   input_date.style.border = '1px solid #ccc';   
       }
          
       
      
      });
      
      
      
      $("#publish_date").blur(function() {
          // claim date validation.  
    	 var valid_date = true; 
    	 var date = $("#publish_date").val();
    	 var input_date =  document.getElementById("publish_date");
    	 
    	 date_year =  date.substring(0,4);
    	 date_month = date.substring(5,7);
    	 date_day =   date.substring(8,10);
    	 
    		
    	
       if (isNumeric(date_year) == false ||  date_year.length != 4 ) {
            valid_date = false; 
       }else if ( isNumeric(date_month) == false ||  date_month.length != 2  || check_month_count(date_month) == false ) { 
    	   valid_date = false;
       }else if ( isNumeric(date_day) == false ||  date_day.length != 2  || check_days_count(date_day, date_month) == false ) { 
    	   valid_date = false;
       } else { 
    	   valid_date = true;
       }
       
       
       if (valid_date == false ) { 
    	   
    	   $("#valid_date_error").html("Valid date format is YYYY-MM-DD for eg. 2009-03-27").show().fadeOut(7000);
    	   input_date.style.border = '1px solid #E76757';
       }else { 
    	   input_date.style.border = '1px solid #ccc';   
       }
          
       
      
      });
      
      
      
      
      function check_month_count(mo) { 
   	   
   	   if (mo <= 12 ) { 
   		   return true; 
   	   }else { 
   		   return false; 
   	   }
   	   
      }
      
     function check_days_count(da, mo) { 
   	     // this need to be extended to validate dates in month of 28 or 29 or 30 days. 
   	   if (da <= 31 ) { 
   		   return true; 
   	   }else { 
   		   return false; 
   	   }
   	   
      }
     
     function isNumeric(my_value) {
		 	if (my_value.match(/^\d+$/) == null)
			 return false;
			else
 		return true;
     }
     
     
     
     $('#GeneratePass').click( function(f) {

       	function randomString() {
 			var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
 			var string_length = 6;
 			var randomstring = '';
 			for (var i=0; i<string_length; i++) {
 				var rnum = Math.floor(Math.random() * chars.length);
 				randomstring += chars.substring(rnum,rnum+1);
 		    }
 	      return randomstring;
          }

       	var myRandomValue = randomString();
      	document.getElementById("reg_new_password").value = myRandomValue;
     	$("#GeneratePass").hide(); 
    	$("#ClearPass").show();

      });
     
      $('#ClearPass').click( function(f) {

       	document.getElementById("reg_new_password").value = '';
       	$("#ClearPass").hide(); 
       	$("#GeneratePass").show(); 

       });
      
      
      $('#artist_name').change( function(f) {
         
    	  if (document.getElementById('artist_name').value != '#' )
          {  
    		  document.getElementById('new_artist_name').value = ''; 
        	  $('#new_artist_name').attr('class', ''); 
          } 
    	  else 
    	  { 
    		  $('#new_artist_name').attr('class', 'textbox');  
    		  $('#artist_name').attr('class', 'selectmenu');   
    	  }
    	  
    	     
      });
      
      
     $('#new_artist_name').keyup(function(){
        
        if (document.getElementById('new_artist_name').value != '')
        { 
        	document.getElementById('artist_name').value = '#'
        	$('#artist_name').attr('class', ''); 
        }
        else 
        {   
           $('#new_artist_name').attr('class', 'textbox');  
   		     $('#artist_name').attr('class', 'selectmenu');   
        	
        }
        
       

     });
    
      
      
      
      
      
  

});





