/****************************************************************************
 * Copyright (c) 1998-2007 Luna Imaging, Inc.  All Rights Reserved.
 *
 * This software is confidential and proprietary information of
 * Luna Imaging, Inc.  ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Luna Imaging, Inc.
 *
 * The software may not be copied, reproduced, translated or reduced to
 * any electronic medium or machine-readable form without
 * the prior written consent of Luna Imaging.
 *
 * You are not allowed to distribute the binary and source code
 * (if released) to third parties, without the prior written consent from
 * Luna Imaging.
 *
 * You are not allowed to reverse engineer, disassemble or decompile
 * code, or make any modifications of the binary or source code, remove
 * or alter any trademark, logo, copyright or other proprietary notices,
 * legends, symbols, or labels in the Software.
 *
 * You are not allowed to sub-license the Software or any derivative
 * work based on or derived from the Software.
 *
 * LUNA IMAGING MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT
 * NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
 * A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, LUNA IMAGING SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 *
 *  cruiz10020@yahoo.com
 *
 *  insight.js
 *
 *  Description:
 *    Common insight functions used through out the site
 *
 *  Structure:
 *
 *
 *  Requires:
 *    prototype.js - http://www.prototypejs.org/
 *    YUI - http://developer.yahoo.com/yui/
 *
 *  Development History:
 *    6-13-2007   cruiz    - created
 *
 *******************************************************************************/

function openHelp( url )
{
  openNewWindow( url, 'Help' );
}

function openNewWindow( url, windowName )
{
  if( url && windowName )
  {
    window.open( url, windowName );
  }
}

var workspaceWindowHandle = null;
function getWorkspaceWindow()
{
  if( ! workspaceWindowHandle || workspaceWindowHandle.closed )
  {
    // open window without changing location, incase it was already open
    workspaceWindowHandle = window.open( '', 'Workspace', 'resizable=yes,scrollbars=no,location=yes,status=no,toolbar=yes,menubar=no' );

    // if we are opening it for the first time OR
    // if for some reason we are not on the workspace url lets set the url
    var index = workspaceWindowHandle.location.href.indexOf( workspaceUrl );
    if( index < 0 )
    {
      workspaceWindowHandle.location.href = workspaceUrl;
    }
  }

  if( workspaceWindowHandle )
  {
    setMainWindowToWorkspace( window );
  }

  return workspaceWindowHandle;
}

function focusWorkspaceWindow()
{
  getWorkspaceWindow().focus();
}

function openRecentlyCreatedPresentation( theParent, forceOpenWorkspace )
{
  // assumes pid is a presentation owned by the user
  if( ( forceOpenWorkspace != true ) && ( ! workspaceWindowHandle || workspaceWindowHandle.closed ) )
  {
    // this is to prevent popup blockers block if we dont have the workspace open
    var postFunction = function(){ openRecentlyCreatedPresentation( theParent, true ); };
    messageUser( "The presentation has been created, please click Ok to open it in the Workspace.", theParent, postFunction );
  }
  else
  {
    // do we have the workspace and is it ready?
    var workspace = getWorkspaceWindow();
    if( workspace.workspaceInitialized == true )
    {
      setTimeout(
        function()
        {
          // workspace must be good to go, lets request some slides
          focusWorkspaceWindow()

          // open the recently created presentation
          workspace.requestFetchAddPresentationToWorkspace();
        },
        2000 );
    }
    else
    {
      var par = theParent;
      setTimeout( function(){ openRecentlyCreatedPresentation( par, true ) }, 500 );
    }
  }
}

function openPresentationInWorkspace( pid, theParent )
{
  if( pid )
  {
    // do we have the workspace and is it ready?
    var workspace = getWorkspaceWindow();
    if( workspace && ( workspace.workspaceInitialized == true ) )
    {
      // even thought the workspace is ready, lets make this call in a bit
      // just to give anything that maybe working to settle down.
      setTimeout(
        function()
        {
          // workspace must be good to go
          focusWorkspaceWindow()

          // lets request some slides
          workspace.slidesPanel.open();
          workspace.slidesPanel.requestSlides( pid );

          if( theParent )
          {
            var obj = $(theParent);
            setTimeout( function(){ ElementEffects.blinkColor( obj, 3, 120 ); }, 1000 );
          }
        },
        1000 );
    }
    else
    {
      var presId = pid;
      var par = theParent;
      setTimeout( function(){ openPresentationInWorkspace( presId, par ) }, 500 );
    }
  }
}

function setMainWindowToWorkspace( mainLunaWindow )
{
  if( workspaceWindowHandle )
  {
    workspaceWindowHandle.mainLunaWindow = mainLunaWindow;
  }
}

function addImageToWorkspace( mid, parent )
{
  if( mid )
  {
    var sUrl = addImageToWorkspaceUrl;
    sUrl = jshAppendParameter( sUrl, 'mid', mid, true );
        
    sMgid = jshGetAfterLastSlashFromUrl( window.location.href ); //first try grabbing the mgid from url in group view
    if( jshIsNumeric( sMgid ) )
      sUrl = jshAppendParameter( sUrl, 'mgid', sMgid, true );
    else
    { // didn't get the mgid, now check detail view url
      var currentUrl = window.location.href;
      var params = currentUrl.toQueryParams();
      if( params['qvq'] )
      {
        var fieldValueMap = getQuickViewFieldValueMap( params['qvq'] );
        if( fieldValueMap['mgid'] )
        {
          sUrl = jshAppendParameter( sUrl, 'mgid', fieldValueMap['mgid'], false );
        }
      }
    }
    var callback =
    {
      success: workspaceActionResponse,
      failure: actionResponse,
      argument: parent,
      timeout: 15000 // time out at 15 sec
    }
 
    // make call
    var transaction = YAHOO.util.Connect.asyncRequest( 'POST', sUrl, callback, null );

    // call for a workspace window now,
    // otherwise browsers might think its a unwanted pop
    getWorkspaceWindow();
  }
}

function addImageToDefaultGroup( mid, parent )
{
  if( mid )
  {
    var sUrl = addImageToDefaultGroupUrl;
    sUrl = jshAppendParameter( sUrl, 'mid', mid, true );

    //alert( 'sUrl: ' + sUrl );

    var callback =
    {
      success: defaultGroupActionResponse,
      failure: actionResponse,
      argument: parent,
      timeout: 10000 // time out at 10 sec
    }

    // make call
    var transaction = YAHOO.util.Connect.asyncRequest( 'POST', sUrl, callback, null );
  }
}

function addImageToGroup( mid, mgid, errorMsg )
{
  if( mid && mgid )
  {
    var sUrl = addImageToGroupUrl;
    sUrl = jshAppendParameter( sUrl, 'mid', mid );
    sUrl = jshAppendParameter( sUrl, 'mgid', mgid, true );

    //alert( 'sUrl: ' + sUrl );

    var callback =
    {
      success: groupActionResponse,
      failure: actionResponse,
      timeout: 10000 // time out at 10 sec
    }

    // make call
    var transaction = YAHOO.util.Connect.asyncRequest( 'POST', sUrl, callback, null );
  }
  else if( !mgid )
  {
  	alert( errorMsg );
  }
}

// Case 758: handle changing of default group
function changeDefaultGroup( mgid )
{
  if ( mgid )
  {

    var sUrl = changeDefaultGroupUrl;
    //sUrl += '&rand=' + Math.random();
    sUrl = jshAppendParameter( sUrl, 'mgid', mgid );

    var callback =
    {
      success: changeDefaultGroupActionResponse,
      failure: function( o ) { }
    }

    var transaction = YAHOO.util.Connect.asyncRequest( 'POST', sUrl, callback, null );
  }
}

// Case 758: handle changing of default group
function deleteGroup( mgid )
{
  if ( mgid )
  {

    var sUrl = deleteGroupUrl;
    sUrl = jshAppendParameter( sUrl, 'mgid', mgid );

    var callback =
    {
      success: deleteGroupActionResponse,
      failure: function( o ) { }
    }

    var transaction = YAHOO.util.Connect.asyncRequest( 'POST', sUrl, callback, null );
  }
}

function deletePresentation( pid )
{
  if ( pid )
  {

    var sUrl = deletePresentationUrl;
    sUrl = jshAppendParameter( sUrl, 'pid', pid );

    var callback =
    {
      success: reloadWindow,
      failure: reloadWindow
    }

    var transaction = YAHOO.util.Connect.asyncRequest( 'POST', sUrl, callback, null );
  }
}

function reloadWindow() {
    window.location.reload();
}

function deleteFolder ( fid )
{
  if ( fid )
  {

    var sUrl = deleteFolderUrl;
    sUrl = jshAppendParameter( sUrl, 'fid', fid );

    var callback =
    {
      success: function( o ) { },
      failure: function( o ) { }
    }

    var transaction = YAHOO.util.Connect.asyncRequest( 'POST', sUrl, callback, null );
  }
}

function workspaceActionResponse( o )
{
  // tell workspace to grab any added items
  //var workspaceHandle = getWorkspaceWindow();
  var workspaceHandle = workspaceWindowHandle;
  if( workspaceHandle && workspaceHandle.requestAddedImages )
    workspaceHandle.requestAddedImages();

  if( o )
  {
    // since right before this we are fetching and adding an image to the
    // workspace ( browser is doing a lot of work )lets wait a bit before
    // we blink that way its a bit more smooth
    var obj = $( o.argument );
    setTimeout( function(){ ElementEffects.blinkBorder( obj, 3, 120 ); }, 500 );
  }
}


function groupActionResponse( o )
{
  if( o )
  {
    // since right before this we are sdding an image to the
    // mediaGroup lets wait a bit before
    // we blink that way its a bit more smooth
    setTimeout( function(){ ElementEffects.blinkBorder( $( 'AddMediaToGroupButton' ), 3, 120 ); }, 500 );
  }
}

function defaultGroupActionResponse( o )
{
  if( o && o.responseText )
  {
    var theResponse = jshEvalJSON( o.responseText, 1 );
    if( theResponse && ( theResponse.statusCode != 1 ) )
    {
      messageUser( theResponse.message, $( o.argument ) );
    }
    else
    {
      ElementEffects.blinkBorder( $( o.argument ), 3, 120 );
      //reloadWindow();
      if (imagesPanel && (imagesPanel.getDefaultMediaGroupId() > 0)){
      	  imagesPanel.requestImages(imagesPanel.getDefaultMediaGroupId()); 
      }      
    }
  }
}

// Case 758: handle changing of default group
function deleteGroupActionResponse( o )
{
  window.location.reload();
}
// Case 758: handle changing of default group
function changeDefaultGroupActionResponse( o )
{
  window.location.reload();
}

function actionResponse( o )
{
  if( o && o.responseText )
  {
    var theResponse = parseResponse( o.responseText )
    messageUser( theResponse.message, o.argument );
  }
}

// this is used by custom action responses
function parseResponse( responseText )
{
  return eval( '(' + responseText + ')' );
}

// this may be upgraded to popup div

function messageUser( message, parent, postFunction )
{
  if ( message )
  {
    message = message.replace(/\n/g, '<br />');

    var popupDiv = $( 'MessageToUserContainer' );
    if( popupDiv.initialized != true )
    {
      popupDiv.style.position = "absolute";

      popupDiv.mMessageHeader = $( document.createElement( 'em' ) );
      popupDiv.mMessageContainer = $( document.createElement( 'p' ) );

      popupDiv.mMessageButton = $( document.createElement( 'a' ) );
      popupDiv.mMessageButton.href = 'javascript:var clickToClose;';
      popupDiv.mMessageButton.style.zIndex = 99999;
      var pf = postFunction;
      popupDiv.mMessageButton.onclick = function(){ popupDiv.mMessageButton.blur(); if(pf){pf();} };
      popupDiv.mMessageButton.onblur = function(){ popupDiv.toggle(); };

      popupDiv.appendChild( popupDiv.mMessageHeader );
      popupDiv.appendChild( popupDiv.mMessageContainer );
      popupDiv.appendChild( popupDiv.mMessageButton );

      popupDiv.mMessageHeader.update( 'Message:' );
      popupDiv.mMessageButton.update( 'ok' );

      popupDiv.initialized = true;
    }

    var offset = null;
    if( parent )
    {
      offset = Position.cumulativeOffset( parent );
    }
    else
    {
      offset = jshGetWindowSize();
      offset[0] = (offset[0] / 2) - 150;
      offset[1] = (offset[1] / 2) - 275;
    }
    var heightOffset = 0;
    if( parent )
     heightOffset = parent.getHeight() / 2;

    var position = [ Math.round( offset[0] + 5 ), Math.round( offset[1] + heightOffset ) ];

    position[0] = Math.max( 0, position[0] );
    position[0] = Math.min( position[0], position[0] + popupDiv.getWidth() );

    popupDiv.style.left = (position[0]) + "px";
    popupDiv.style.top = (position[1]) + "px";

    // update content
    popupDiv.mMessageContainer.update( message );

    // lets show it.
    popupDiv.show();
    popupDiv.style.visibility = 'visible';
    popupDiv.mMessageButton.focus();
  }

  return;
}

function closeMessageUser()
{
  var popupDiv = $( 'MessageToUserContainer' );
  popupDiv.hide();
}

// add to text inputs
// Example: <input ... onclick="clearTitleText( this, 'Search Groups...');" >
function clearTitleText( element, titleText )
{
  if ( element.value == titleText ) element.value = "";
}

function addElement( parent, child )
{
  parent[parent.length] = child;
}


// used to populate folder tree for various pages
// turn the flat folder structure into multi-demensional array for TreeControl
function wireUpFolders(folders, folderInfo)
{
  for ( i=1; i<folderInfo.length; i++ )
  {
    myId = folderInfo[i][0];
    parentId = folderInfo[i][1];

    // add each folder to it's parent folder
    addElement( getParentFolder(parentId, folders), folders["id" + myId] );
  }
}

// If parent folder doesn't exist for some reason, put this folder in root folder.
// Parent folder should always exist.
// But just in case something goes wrong the system is fault tolerant.
function getParentFolder(parentId, folders)
{
  return (folders["id" + parentId] != null ) ? folders["id" + parentId] : folders["id0"];
}

function debug( debugText )
{
  if ($("debugger")) $("debugger").value = debugText;
  //else alert(debugText);
}


function goBack( url )
{
  document.location.href = url;
}

function redirectToLogin( mediaId )
{
  if ( mediaId )
  {
    var sUrl = loginAddMediaToDefaultGroupUrl;
    // add the media id so controller can grab it
    sUrl = sUrl + '/' + mediaId;

    document.location.href = sUrl;
  }
}

function constructQuickViewUrl( currentUrl, destinationUrl, mediaIndex, totalResultsSize )
{
  var query = [];
  if( destinationUrl )
  {
    if( ! currentUrl )
      currentUrl = window.location.href;

    var params = currentUrl.toQueryParams();
    var cleanUrl = jshGetCleanUrl( currentUrl );
    var sort = '';
    var q = '';
    var w4s = '';
    var mgid = '';
    var myMedia = '';

    var gidRegx = /.*\/[0-9]+\/?$/;
    var w4Regx = /.*\/what|where|when|who\/?\??.*$/;
    if( cleanUrl.match( w4Regx ) )
    {
      // W4s
      var rxp = new RegExp( /\/what|where|when|who\/?\??.*$/ );
      var matches = rxp.exec( cleanUrl );
      if( matches && ( matches.index > 0 ) )
      {
        w4s = cleanUrl.substring( matches.index, cleanUrl.length );
      }
    }
    else if( ( cleanUrl.match( gidRegx ) ) || params['mgid'] )
    {
      // grab the mgid from all possible sources
      // its a parameter
      if( params['mgid'] )
      {
        mgid = params['mgid'];
      }
      else
      {
        // must be part of the url
        if( cleanUrl.charAt( cleanUrl.length - 1 ) == '/' )
          cleanUrl = cleanUrl.substring( 0, cleanUrl.length - 1 );

        mgid = cleanUrl.substring( cleanUrl.lastIndexOf( '/' ) + 1, cleanUrl.length );
      }
    } else if(cleanUrl.indexOf('/myMedia') >0 ) {
    	myMedia = true;
    }
    	
    
    // build up the quickView query
    if( w4s )
    {
      if( w4s.charAt( 0 ) != '/' )
        w4s = '/' + w4s;

      query.push( 'w4s:' + w4s );
    }
    if( params['q'] )
    {
      var q = params['q'];
      var index = q.indexOf( 'LIMIT:' );
      if( index > 0 )
      {
        q = q.substring( 0, index );
      }

      query.push( 'q:' + q );
    }
    if( params['sort'] )
    {
      query.push( 'sort:' + params['sort'] );
    }

    if( mgid )
    {
      query.push( 'mgid:' + mgid );
    }
    else if(myMedia) {
    	query.push('myMedia:true');
    }else
    {
      // only toss in the collections if we are not in a group
      if( params['cic'] )
      {
        query.push( 'lc:' + params['cic'] );
      }
    }

    destinationUrl = jshAppendParameter( destinationUrl, 'qvq', query.join( ';' ), false );
    if( mediaIndex >= 0 )
    {
      destinationUrl = jshAppendParameter( destinationUrl, 'mi', mediaIndex, false );
    }
    if( totalResultsSize >= 0 )
    {
      destinationUrl = jshAppendParameter( destinationUrl, 'trs', totalResultsSize, false );
    }

    return destinationUrl;
  }
}

function constructQuickViewQuery( currentUrl )
{
  var query = '';
  var params = currentUrl.toQueryParams();
  if( params['qvq'] )
  {
    var fieldValueMap = getQuickViewFieldValueMap( params['qvq'] );

    query = '/';
    if( fieldValueMap['w4s'] )
    {
      query = fieldValueMap['w4s'];
    }

    if( fieldValueMap['q'] )
    {
      query = jshAppendParameter( query, 'q', fieldValueMap['q'], false );
    }
    if( fieldValueMap['sort'] )
    {
      query = jshAppendParameter( query, 'sort', fieldValueMap['sort'], false );
    }
    if( fieldValueMap['mgid'] )
    {
      query = jshAppendParameter( query, 'mgid', fieldValueMap['mgid'], false );
    }
    if(fieldValueMap['myMedia']) 
    {
      query = jshAppendParameter( query, 'myMedia', fieldValueMap['myMedia'], false );
    }    
    if( fieldValueMap['lc'] )
    {
      query = jshAppendParameter( query, 'lc', fieldValueMap['lc'], false );
    }
  }

  return query + '&sort=' + params['sort'];
}

function getQuickViewFieldValueMap( qvq )
{
  var fieldValueMap = null
  if( qvq )
  {
    var args = qvq.split( ';' );
    fieldValueMap = $({});
    var fieldValuePair;
    for( var i = 0; i < args.length; i++ )
    {
      if( args[i] )
      {
        fieldValuePair = args[i].split( ':' );
        if( fieldValuePair.length == 2 )
        {
          fieldValueMap[fieldValuePair[0]] = fieldValuePair[1];
        }
      }
    }
  }

  return fieldValueMap
}

function constructQuickViewThumbnailUrl( mediaGroupPrefixUrl, viewAllPrefixUrl, searchPrefixUrl,myMediaPrefixUrl, requestParams, offset, pgs )
{
  var toReturn = '';
  var fieldValueMap = getQuickViewFieldValueMap( requestParams['qvq'] );
  if( fieldValueMap )
  {
    if( fieldValueMap['mgid'] )
    {
      if( mediaGroupPrefixUrl.charAt( mediaGroupPrefixUrl.length - 1 ) != '/' )
      {
        mediaGroupPrefixUrl += '/';
      }

      toReturn = mediaGroupPrefixUrl + fieldValueMap['mgid'];
      if( fieldValueMap['sort'] )
      {
        toReturn = jshAppendParameter( toReturn, 'sort', fieldValueMap['sort'], false );
      }
    }
    else if( fieldValueMap['q'] )
    {
      toReturn = searchPrefixUrl;
      if( fieldValueMap['w4s'] )
      {
        toReturn += fieldValueMap['w4s'];
      }

      toReturn = jshAppendParameter( toReturn, 'q', fieldValueMap['q'], false );

      if( fieldValueMap['sort'] )
      {
        toReturn = jshAppendParameter( toReturn, 'sort', fieldValueMap['sort'], false );
      }
    }
    else if( fieldValueMap['lc'] )
    {
      toReturn = viewAllPrefixUrl;
      if( fieldValueMap['w4s'] )
      {
        toReturn += fieldValueMap['w4s'];
      }

      // we do this so that we do not change what collections are currently in context
      var limitQuery = 'LIMIT: ' + fieldValueMap['lc'];
      toReturn = jshAppendParameter( toReturn, 'q', limitQuery, false );

      if( fieldValueMap['sort'] )
      {
        toReturn = jshAppendParameter( toReturn, 'sort', fieldValueMap['sort'], false );
      }
    }
    else if(fieldValueMap['myMedia'] && fieldValueMap['myMedia']=='true')
    {
      toReturn = myMediaPrefixUrl;
    }

    // tack on offset
    if( toReturn.length > 0 )
    {
      var os = offset;
      if( pgs > 0 )
      {
        os = offset - ( offset % pgs );
      }

      toReturn = jshAppendParameter( toReturn, 'os', os, false );
    }
  }
  return toReturn;
}

function getQuickViewMediaGroupId( currentUrl )
{
  if( ! currentUrl )
    currentUrl = window.location.href;
    
  var params = currentUrl.toQueryParams();
  if( params['qvq'] )
  {
    var fieldValueMap = getQuickViewFieldValueMap( params['qvq'] );
    if( fieldValueMap['mgid'] )
    {
      return fieldValueMap['mgid'];
    }
  }
  return null;
}

function constructReturnToSourceUrl( widgetUrl )
{
  var toReturn = jshGetCleanUrl( widgetUrl );
  var params = widgetUrl.toQueryParams();
  for( var key in params )
  {
    if( params[key] )
    {
      if( ( key.toLowerCase() != 'embedded' ) &&
          ( key.toLowerCase() != 'fromwidgetcreator' ) &&
          ( key.toLowerCase() != 'widgetformat' ) &&
          ( key.toLowerCase() != 'controls' ) )
      {
        toReturn = jshAppendParameter( toReturn, key, params[key] );
      }
    }
  }

  return toReturn;
}


function getScrollTop() {
  if ( document.documentElement.scrollTop )
    return document.documentElement.scrollTop;

  return document.body.scrollTop;
}

function scrollHandler() {
   var e = document.getElementById('waitMessageContainer');
   e.style.top = getScrollTop();
}

function showNotify( str ) { 
  var elem = document.getElementById('waitMessageContainer');
  elem.style.display = 'block'; 
  elem.style.visibility = 'visible';

  if ( elem.currentStyle && 
       elem.currentStyle.position == 'absolute' ) 
  {
    elem.style.top = getScrollTop();
    window.onscroll = scrollHandler;
  }

  elem.innerHTML = str;
}

function loadMessage( str ) {

  window.setTimeout("showNotify('" + str + "');", 1000);
  window.setTimeout("hideNotify();",10000);
  return true; 

}


