﻿//******************************************************************************
// Author: Riccardo La Rosa
// Date: 1/5/2007
// File: RunEzGeneral.js
// Description: Utility functions used across the site 
//******************************************************************************

//
function copyToClipboard(inElement) {
  if (inElement.createTextRange) {
    var range = inElement.createTextRange();
    if (range)
     range.execCommand('Copy');
  } else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="Images/_clipboard.swf" FlashVars="clipboard='+escape(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}

// Loads the loginform from the parent WorldView
function ShowLoginForm()
{
    var logfrm;
    if (parent != self)
        logfrm = parent.$('loginform');
    else
        logfrm = $('loginform');
    
    new Effect.SlideDown(logfrm);
}

//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}

}

//*******************************************
// Function: SubmitEnter
// Description: adapted from http://www.htmlcodetutorial.com/forms/index_famsupp_157.html
// Author: Riccardo La Rosa
//*******************************************
function SubmitEnter(myfield,e,btnToClickId)
{
    var keycode;
    if (window.event) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;

    if (keycode == 13)
       {
           $(btnToClickId).click();
           return false;
       }
    else
        return true;
}

//*******************************************
// Function: DisplayPlaylist
// Description:
// Author: Mihir Mange
//*******************************************


function DisplayPlaylist(playlistId)
{

    if (parent != self)
        parent.DisplayPlaylist(playlistId);
    else
        new Lightbox.base('Playlist'); 
        
    
    GetPlaylistInfo(playlistId);
	
}   
    
    
//*******************************************
// Function: ShowGroupTagsForm
// Description:
// Author: Riccardo La Rosa
//*******************************************
function ShowGroupTagsForm() {

    $("tagadderlink").style.display="none";
    $("tagadder").style.display="";
    
}


//*******************************************
// Function: ShowRouteTagsForm
// Description:
// Author: Mihir Mange
//*******************************************
function ShowRouteTagsForm(fieldname) {
    $("tagadderlink").style.display="none";
    $("tagadder").style.display="";
    $(fieldname).focus();
}


//*******************************************
// Function: HideTagsForm
// Description:
// Author: Mihir Mange
//*******************************************
function HideTagsForm() {
    $("tagadderlink").style.display="none";
    $("tagadder").style.display="none";
}


//*******************************************
// Function: AddGroupTag
// Description:
// Author: Riccardo La Rosa
//*******************************************
function AddGroupTag(groupId, tagName)
{    
    // check if tagname is empty
    if (tagName == '')
        return;
    
    //prepare the ajax request
    var url = "/RunEasy/AjaxRequests/AddGroupTags.aspx";
    var params = "TagName="+tagName+"&groupId="+groupId;

    //send the request and update the 'thegrouptags' div
    var ajax = new Ajax.Updater(
            'thegrouptags',
            url,
            {method: 'get',parameters: params, evalScripts:true}
    );
  
    return false;
}

//*******************************************
// Function: AddRouteTag
// Description:
// Author: Mihir Mange
//*******************************************
function AddRouteTag(routeId, fieldname)
{

    var tagName = $F(fieldname);

    // check if tagname is empty
    if (tagName == '')
        return;
    
    //prepare the ajax request
    var url = "/RunEasy/AjaxRequests/ViewRun/AddRouteTags.aspx";
    var params = "TagName="+tagName+"&routeId="+routeId;

    //send the request and update the 'thegrouptags' div
    var ajax = new Ajax.Updater(
            'theroutetags',
            url,
            {method: 'get',parameters: params, evalScripts:true}
    );
    
    //$("tagadderlink").style.display="";
    //$("tagadder").style.display="none";
    $(fieldname).value = '';
    
    return false;
}

//*******************************************
// Function: getAvlGroups
// Description: This function makes an AJAX
// call to getAvlGroup.aspx which returns
// a dropdown populated with the groups
// available to the current user to be able
// to add to the route.
// Author: Mihir Mange
//*******************************************
function getAvlGroups(routeId)
{    

    $("groupadderlink").style.display="none";
    $("groupadder").style.display="";
   
    //prepare the ajax request
    var url = "/RunEasy/AjaxRequests/ViewRun/GetAvlGroups.aspx";
    var params = "routeId="+routeId;

    //send the request and update the 'thegrouptags' div
    var ajax = new Ajax.Updater(
            'groupadder',
            url,
            {method: 'get',parameters: params, evalScripts:true }
    );
    
    //$("ddlAvlGroups").focus();          
    return false;
}


//*******************************************
// Function: SendGroupToRoute
// Description:
// Author: Mihir Mange
//*******************************************
function SendGroupToRoute(routeId, ddlAvlGroups)
{
	var ddlIndex  = ddlAvlGroups.selectedIndex
	var groupId = ddlAvlGroups.options[ddlIndex].value
	
	if (ddlIndex == 0)
	  return false;
	if (groupId == "")
	  return false;
	
    //prepare the ajax request
    var url = "/RunEasy/AjaxRequests/ViewRun/SendRouteToGroup.aspx";
    var params = "groupId="+ groupId + "&routeId=" + routeId;

    //send the request and update the 'thegrouptags' div
    var ajax = new Ajax.Updater(
            'theroutegroups',
            url,
            {method: 'get',parameters: params, evalScripts:true}
    );
    return false;
}


//*******************************************
// Function: AddNewPlaylist
// Description: passes a form to an ajax form
//              which add's a playlist, or
//              shows an existing playlist.
// Author: Mihir Mange
//*******************************************
function AddPlaylist(theForm, controls)
{
    
    $(controls["lblmixRequired"]).style.display="none";
    //$('lblNameRequired').style.display="none";
    
    var imixCode = $F(controls["txtIMixCode"]);
    var plName = $F(controls["txtPLName"]);
    
    // check if tagname is empty
    if (imixCode == '')
    {
        $(controls["lblmixRequired"]).style.display="";
        return false;
    }else if( plName == '' )
    {
        $(controls["lblNameRequired"]).style.display="";
        return false;
    }
    else
    {   
        //formString = Form.serialize( theForm );
        var url = "/RunEasy/AjaxRequests/CreatePlayList.aspx";
        var params = "imixCode=" + encodeURIComponent(imixCode) + "&plName=" + plName;
        
        var myAjax = new Ajax.Updater(
            'newpls',
            url, { method: 'post', parameters: params , evalScripts:true} );
    }
    
    return false;
}

//*******************************************
// Function: clearPlaylistForm
// Description: clears the playlist form on 
//              playlist directory page.
// Author: Mihir Mange
//*******************************************
function clearPlaylistForm()
{
    //$('txtPLName').value = '';
    //$('txtIMixCode').value = '';
    new Effect.SlideUp('playlistfrm'); 
    //$('hlCreateNewPlayList').style.display='';  
}


//********************************
//FUNCTION: sndReqByUser
//DESC: this is the ajax function that updates the rating by user
//AUTHOR: Riccardo La Rosa
//USED ON: PlaylistDirectory.aspx, ProcessUserRating.aspx
//MODIFIED/ENHANCED: Mihir Mange
//********************************
function sndReqByUser(itemId, itemType , rating) {

    //get the div that we are updating for the total score
    var elem = $('StarRating_'+ itemType + "_" + itemId);
    elem.innerHTML = '<em>Loading ...</em>';
	//prepare the ajax request
	var url = "/RunEasy/AjaxRequests/ProcessUserRating.aspx";    
    var params = "rating="+rating;    
    if( itemType == "playlist")
        params = params + "&playlistId=" + itemId ;
    if( itemType == "route" )
        params = params + "&routeId=" + itemId;
    
    //Added by Radhita on 04/24/07 for Video Ratings
    if ( itemType == "video" )
        params = params + "&videoId=" + itemId ;
        
    var ajax = new Ajax.Updater(
            'StarRating_'+ itemType + "_"+ itemId,
            url,
            {method: 'get',parameters: params,onFailure: reportError}
    );
    
}

function reportError(request) {
    var elName = "Star_Rating" + itemType + "_" + itemId;
    $F(elName) = "Error";
}

function sndReqByUser_response(response)
{
 // put returned HTML in the div
 $('StarRating_').innerHTML = response.responseText;

}


//********************************
//FUNCTION: browsePlaylist
//DESC: This is the ajax function that is responsible
//      for getting the results using the sort field, 
//      and expression
//USED ON: PlaylistDirectory.aspx
//AUTHOR: Mihir Mange
//********************************
function browsePlaylist(pageNumber, pageSize)
{
    var sortExpression = $('sortExpression').options[$('sortExpression').selectedIndex].value ;
    var sortOrder = $('sortOrder').options[$('sortOrder').selectedIndex].value ;
    
    //get the div that we are updating for the total score
    var elem = $('results');
    elem.innerHTML = '<em>Loading...</em>';

    var url = "/RunEasy/AjaxRequests/BrowsePlaylists.aspx";    
    var params = "pageNumber="+pageNumber +"&pageSize=" + pageSize + "&sortExpression=" + sortExpression + "&sortOrder=" + sortOrder;    

    var ajax = new Ajax.Updater(
            'results',
            url,
            {method: 'get',parameters: params,evalScripts:true}
    );
}

function browseReplies(topicId, pageNumber, pageSize, totalCount)
{    
    
    //get the div that we are updating for the total score
    var elem = $('results');
    elem.innerHTML = '<em>Loading...</em>';

    var url = "/RunEasy/AjaxRequests/BrowseReplies.aspx";    
    var params = "pageNumber="+pageNumber +"&pageSize=" + pageSize + "&topicId=" + topicId + "&totalCount=" + totalCount; 

    var ajax = new Ajax.Updater(
            'results',
            url,
            {method: 'get',parameters: params, evalScripts:true}
    );
}


//********************************
//FUNCTION: addPlaylistToRoute(playlistId, playlistName)
//DESC: This function gets the parent iframe and 
//      sets the some variables related to the playlist
//      in the parent iframe.
//USED ON: PlaylistDirectory.aspx
//AUTHOR: Mihir Mange
//********************************
function addPlaylistToRoute(playlistId, playlistName)
{   
    parent.document.getElementById('playlistName').innerHTML = gLbPlayListSet + "<b>"+playlistName+"</b>";
    parent.document.getElementById('txtPlaylistId').value = playlistId;
    parent.document.getElementById('playlistiframe').style.display = 'none';    
}

//********************************
//FUNCTION: cancelAddPlaylist(
//DESC: This function cancels the adding
//USED ON: PlaylistDirectory.aspx
//AUTHOR: Paul Irish
//********************************

function cancelAddPlaylist()
{   
    parent.document.getElementById('txtPlaylistId').value = '';
    parent.document.getElementById('playlistiframe').style.display = 'none';    
}


//********************************
//FUNCTION: setPls()
//DESC: This function makes the iframe visible to set
//      the playlist for a route.. 
//USED ON: CreateRun.aspx
//AUTHOR: Mihir Mange
//********************************
function setPls(){
	if ( $('playlistiframe') ) 
	{
		$('playlistiframe').style.display=''; return false;
	}
	else 
	{
		// TODO: FIX THE SCROLLING UNDERNEATH 
		document.getElementsByTagName('body')[0].insertBefore(iframe1, $('doc'));
		getwindowsize();
		$('playlistiframe').style.height=winHeight-10+'px';
		$('playlistiframe').style.width=winWidth-20+'px';
		
	}
}

//*******************************************
// Function: deleteOption
// Description:delete an option from dropdown
// Author: Mihir Mange
//*******************************************
function deleteOption(selectObject,optionRank) {
    if (selectObject.options.length!=0) { selectObject.options[optionRank]=null }
}


//*******************************************
// Function: GetPlaylistInfo
// Description:
// Author: Mihir Mange
//*******************************************
function GetPlaylistInfo(playlistId)
{
	
	
    var url = "/RunEasy/AjaxRequests/ViewRun/GetPlaylistInfo.aspx";
    var params = "playlistId="+playlistId;
    
    //send the req and update the Profile div
    var ajax = new Ajax.Updater('PlaylistInfo', url, {method: 'get', parameters: params, evalScripts:true});
	
	

    
}

//*******************************************
// Function: flagItem
// Description: 
// Author: Mihir Mange
//*******************************************
function flagItem(itemType, itemId, itemContent)
{   
		if ( !confirm('Are you sure you want to report this content as offensive or inappropriate?') )
			return false;
		
		
    //get the div that we are updating for the total score
    elemDivName = 'flag_' + itemType + '_' + itemId ;
    var elem = $(elemDivName);  
 
    var encodedContent = encodeURIComponent(itemContent);
 
    elem.innerHTML = '<em>Loading...</em>';

    var url = "/RunEasy/AjaxRequests/ProcessFlag.aspx";            
    var params = "itemType="+ itemType +"&itemId=" + itemId ;     
    
    if(itemContent != "")
    {
      params = params + "&itemContent=" + encodedContent;
    }
    
    var ajax = new Ajax.Updater(
            elemDivName,
            url,
            {method: 'post',parameters: params, evalScripts:true}
    );
}

//*******************************************
// Function: flagItem
// Description: 
// Author: Mihir Mange
//*******************************************
function EnableDisable(itemType, itemId, func)
{        
    //get the div that we are updating for the total score
    elemDivName = 'ed_' + itemType + '_' + itemId ;
    var elem = $(elemDivName);  
 
    elem.innerHTML = '<em>Loading...</em>';

    var url = "/RunEasy/Admin/AjaxRequests/EnableDisable.aspx";            
    var params = "itemType="+ itemType + "&itemId=" + itemId + "&function=" + func;     
        
    var ajax = new Ajax.Updater(
            elemDivName,
            url,
            {method: 'get',parameters: params, evalScripts:true}
    );
}

//*******************************************
// Function: SendGroupToRoute
// Description:
// Author: Riccardo La Rosa
//*******************************************
function AddRunToMyRuns(routeId, userId,functionAfter)
{
	
    //prepare the ajax request
    var url = "/RunEasy/AjaxRequests/ViewRun/SendRouteToUser.aspx";
    var params = "routeId="+ routeId + "&userId=" + userId;

    //send the request and update the 'IsMyRunStatus' div
    var ajax = new Ajax.Updater(
            'IsMyRunStatus',
            url,
            {
                method: 'get',
                parameters: params,
                evalScripts:true,
                onSuccess: functionAfter
            }
    );
    new Effect.Highlight('IsMyRunStatus', {duration:3} );
}