// -*- js-standard: domwindow, prototype;  -*-

// Please review
// http://wiki.mintel.co.uk/GNPD/JavaScript_and_CSS_guidelines
// before modifing this file

pos_at = undefined;
pos = undefined;

/* General helper & compatibility functions */
ie = document.all;
ns6 = document.getElementById && !document.all;

// array code by Chris Nott (chris[at]dithered[dot]com)
function isUndefined(property) {
  return (typeof property == 'undefined');
}
function isDefined(property) {
  return (typeof property != 'undefined');
}

// Array.concat() - Join two arrays
if (isUndefined(Array.prototype.concat) == true) {
  Array.prototype.concat = function (secondArray) {
     var firstArray = this.copy();
     for (var i = 0; i < secondArray.length; i++) {
        firstArray[firstArray.length] = secondArray[i];
     }
     return firstArray;
  };
}

// Array.push() - Add an element to the end of an array
if (isUndefined(Array.prototype.push) == true) {
  Array.prototype.push = function() {
     var currentLength = this.length;
     for (var i = 0; i < arguments.length; i++) {
        this[currentLength + i] = arguments[i];
     }
     return this.length;
  };
}

   String.prototype.substitute = function(was, becomes) {
       return this.split(was).join(becomes);
   };

   String.prototype.replaceSet = function(matcharray) {
        var s = this;
        for (var i = 0; i < matcharray.length; i += 2)
        {
            s = s.substitute("{" + String(matcharray[i]).trim() + "}", matcharray[i + 1]);
        }

      return s;
   };

// Strip is provided by PrototypeJS, but we've previously been using trim.
String.prototype.trim = String.prototype.strip

function getElementsByName_iefix(tag, name)
{
    return $$(tag + "[name=" + name + "]");
}

function reflow(obj)
{
    obj = $(obj);
    if (obj && obj.style)
    {
        var display_style = obj.style.display;
        obj.style.display = 'none';
        obj.style.display = display_style;
    }
}

//prefer: http://www.prototypejs.org/api/utility/dollar
getobj = $;

// prefer: http://www.prototypejs.org/api/array/clone
function copyArray(origArray)
{
    return origArray.clone();
}

// prefer: http://www.prototypejs.org/api/array/indexof
function arrayIndexOf(array, item)
{
    return array.indexOf(item);
}

// prefer: http://www.prototypejs.org/api/element/getStyle
function getStyle(obj,styleProp)
{
    return $(obj).getStyle(styleProp);
}

current_sort_method = null;

Event.observe(window, "scroll", hideTipContainer);

/** Run a function when an element appears in the DOM, with exponentional
  * backoff */
function runOnElementReady(elId, callback, timeout)
{
    //default timeout in milliseconds
    timeout= timeout || 50;
        
    if (timeout>10000)
        throw "element " + elId + " has not appeared in the DOM";
    
    if ($(elId))
    {
        callback()
    }
    else
    {
        setTimeout(function() { runOnElementReady(elId, callback, timeout*2)},
                   timeout);
    }
}

function createImage (src, title, className)
{
    var img = document.createElement("img");
    img.src = src;
    img.title = title;
    if (className)
        img.className = className;
    return img;
}

/**
 * @brief DOM function that inserts @p newChild as the first child in @p parent.
 */
function insertFirstChild (parent, newChild)
{
    var firstChild = parent.firstChild;
    if (firstChild)
    {
        parent.insertBefore(newChild, firstChild);
    }
    else
    {
        parent.appendChild(newChild);
    }
}

/**
 * Removes the @p node from the DOM to which it belongs.
 */
function removeNode(node)
{
    if (node.parentNode)
        node.parentNode.removeChild(node);
}

/**
 * @param[in] node The new parent node for the children.
 * Every argument after node is added to it with appendChild()
 */
function appendChildren (node)
{
    for (var i = 1; i < arguments.length; i++)
    {
        node.appendChild(arguments[i]);
    }
}

function addSelectOption (select, text, value)
{
    var opt = document.createElement("option");
    opt.text = text;
    opt.value = (value!==undefined)?value:text;
    try
    {
        select.add(opt, null);
    }
    catch (e)
    {
        select.add(opt);
    }
}

function asynchProfileUpdate(property, frontpage)
{
    var value= "";
    var action = (frontpage) ? "update_profile_frontpage" : "update_profile";

    if (property == "preferred_currency")
    {
        var primary = document.getElementById("primary_currency");
        value= (primary.innerHTML.indexOf('$')>-1) ? "dollar" : "euro";
    }
    else if (property == "prefered_measures")
    {
        var measure = $("measurestarget").innerHTML.toLowerCase();
        if (measure == "g"
            || measure == "kg"
            || measure == "litre"
            || measure == "ml"
            || measure == "cl"
            || measure == "cc")
        {
            value = "metric";
        }
        else
        {
            value = "imperial";
        }
    }
    else if (property == "default_ingredients_format")
    {
        var formats = document.getElementsByName("ingredients_type");
        for(j=0;j<formats.length;++j)
        {
          if(formats[j].checked==true)
          {
            value = formats[j].value;
          }
        }        
    }
    else if (property == "vlist" || 
     property == "packaging" || property == "product_description" || 
         property == "annotation"|| property == "product_extras" 
         || frontpage)
    {        
        var state = $(property + "_body").style.display;
        value= (state == "none") ? "Collapsed" : "Expanded";
    }
    if (value)
    {
        var ex_params = "action=" + action + "&" +property+"="+value+"&async";
        var url = "/sinatra/gnpd/my_info/?";
        
        new Ajax.Request(url, {method: 'post', parameters: ex_params });
    }
}

function setEmailAlertAsync()
{
    var search_id = document.getElementById("search_id").value;
    var list_name = 'alerter';
    if (!document.forms['searches'].elements[list_name])
    {
        list_name = 'alert' + search_id;
    }
    var index = document.forms['searches'].elements[list_name].selectedIndex;
    var value = document.forms['searches'].elements[list_name].options[index].value;
    var ex_params;
    var url = "/sinatra/gnpd/saved_searches/?";
    ex_params = "search_id="+search_id+"&"+"set_alert&"+"async&"+"&interval="+value;

    new Ajax.Request(url,
    {
        method: "POST",
        parameters: ex_params,
        onSuccess:  function(transport)
                    {
                        response = transport.responseText
                        if (response == "Email Alert Changed")
                        {
                            $('alertsettermsg').innerHTML = "Updated";
                        }
                        else
                        {
                            $('alertsettermsg').innerHTML = "Error. Try again please.";
                        }
                    },
        onLoading:  function()
                    {
                        $('alertsettermsg').innerHTML = "<img alt='' src='/gnpd/images/loading.gif'> Updating";
                    },
        onFailure:  function(transport)
                    {
                        $('alertsettermsg').innerHTML = "Error. Try again please.";
                    }
    });

}

function saveSearchAsync(redirect, saved_string, force_new)
{
    var ex_params = {};
    var url = "/sinatra/gnpd/saved_searches/";
    var search_id = $("search_id").value;
    
    // undefined appears in the query string as a keys with no value:
    // save_last&async&action=save_search  
    ex_params.save_last = undefined;
    ex_params.async = undefined;
    ex_params.action = "save_search";
    
    if (force_new)
    {          
        ex_params.force_new = undefined;
        ex_params.search_id = 0;
    }
    else
    {
        ex_params.search_id = search_id;
    }
    
    var name = $F("new_saved_search");
    if (name == "<enter new search name>")
        name = "";
    
    ex_params.new_search_name = name;
    
    var select = $("search_alerts_interval");
    var selecthidden = $("hidalerts");
    for (var i=0; select.length; i++)
    {
        if(select[i].selected)
        {
            ex_params.interval = select[i].value;
            if (selecthidden) 
            {
                selecthidden[i].selected=true;
            }
            break;
        }
    }
    
    var save_alert = false;
    if ($("save_focus_page")) 
    {
        ex_params.save_focus_page= undefined;
        ex_params.focus_id= $F("focus_id");
        ex_params.focus_type_id= $F("focus_type_id");
        save_alert = true;
    }
    
    if ($("save_ingredient_alert")) 
    {
        ex_params.save_ingredient_alert= undefined;
        ex_params.ingredient_id= $F("ingredient_id");
        save_alert = true;
    }
    
    new Ajax.Request(url,
                     { method:"POST",
                       parameters: ex_params,
                       onSuccess: function(response)
                                  {
                                      saveSearchAsync_success(response.responseText,
                                                              redirect, saved_string,
                                                              save_alert);
                                  },
                       onFailure: function()
                                  {
                                      var msg = response.responseText || "There was an error while saving your search."; 
                                      show_message("error", "Save Search", msg);
                                  }
                     } );
}

function saveSearchAsync_success(response, redirect, saved_string, save_alert)
{
    var new_id = response;
    $("search_id").value=new_id;

    var hidalerts = $("hidalerts");
    if (hidalerts)
    {
        $("save_search").style.display = 'none';
        $("hidalerts").name = "alert" + new_id;
        $("hidalerts").setAttribute('onchange',"setEmailAlertAsync('"+new_id+"');");
    }
    
    if (save_alert) 
    {
        var set_alert_obj, remove_alert_obj;
        if ((set_alert_obj=$('set_alert')) && (remove_alert_obj=$('remove_alert')))
        {
            $('set_alert').style.display = 'none';
            $('remove_alert').style.display = 'block';
        }
    }

    var ex_params = {search_id: new_id};
    var req = new Ajax.Request("/sinatra/gnpd/rss_link/",
                               { method: "GET",
                                 parameters: ex_params,
                                 onSuccess: 
                                 function(response)
                                 {
                                    if(redirect)
                                    {
                                        window.location = response.responseText;
                                    }
                                    else
                                    {
                                         $("rssfeedlink").href = response.responseText;
                                         $("save_edit_content").innerHTML = saved_string;
                                         $("gotoalerts").style.display = 'inline';
                                         if ($("update_saved_search")) {
                                             $("update_saved_search").hide();
                                         }
                                    }
                                 }
                               } );

    var name = $F("new_saved_search");
    if (name == "<enter new search name>")
        name = "";

    if (name.length != 0)
    {
        var searchDetails = $("heading_search_details");
        if (searchDetails)
        {
            searchDetails.innerHTML = name;
        }
    }
}

function deleteSearchAsync(removed_string)
{
    var ex_params = {};
    
    var url = "/sinatra/gnpd/saved_searches/";
    var search_id = $("search_id").value;
    
    ex_params.async = undefined;
    ex_params.action = "delete_search";    
    ex_params.search_id = search_id;
    
    new Ajax.Request(url,
                     { method:"POST",
                       parameters: ex_params,
                       onSuccess: function(response)
                                  {
                                      var set_alert_obj, remove_alert_obj;
                                      if ((set_alert_obj=$('set_alert')) && (remove_alert_obj=$('remove_alert')))
                                      {
                                          remove_alert_obj.style.display = 'none';
                                          set_alert_obj.style.display = 'block';
                                          $("save_edit_content").innerHTML = removed_string;
                                      }
                                  },
                       onFailure: function()
                                  {
                                      var msg = response.responseText || "There was an error while deleting your search."; 
                                      show_message("error", "Delete Search", msg);
                                  }
                     } );
}

function toggleSearchDetailsFrame()
{
    var el = $("search_details_frame");
    if (!el.style)
        return;

    if (el.style.display == 'none')
    {
        el.style.display = 'block';
        el = $("hide_search_details");
        el.style.display = 'block';
        el = $("hide_search_details_string");
        el.style.display = 'block';
        el = $("show_search_details");
        el.style.display = 'none';
        el = $("show_search_details_string");
        el.style.display = 'none';
        
       
        var target = $("prod_count");
        var source = $("searcdetspan");
        var tmp = target.innerHTML;
        target.innerHTML = source.innerHTML;
        source.innerHTML = tmp;
    }
    else
    {
        el.style.display = 'none';
        el = $("hide_search_details");
        el.style.display = 'none';
        el = $("hide_search_details_string");
        el.style.display = 'none';
        el = $("show_search_details_string");
        el.style.display = 'block';
        el = $("show_search_details");
        el.style.display = 'block';
        
        var target = $("prod_count");
        var source = $("searcdetspan");
        var tmp = target.innerHTML;
        target.innerHTML = source.innerHTML;
        source.innerHTML = tmp;
        
    }
}

/* Saved searches on Analysis page */
function update_search(obj_name)
{
    var form_obj=$(obj_name);

    if (form_obj && form_obj.elements)
    {
        var form_action;
        if ((form_action=form_obj.elements["action"]))
            form_action.value="save_search";

        form_obj.submit();
    }
}

function update_rename_search(obj_name)
{
    var form_obj=$(obj_name);
    if (form_obj && form_obj.elements)
    {
        var form_action;
        if ((form_action=form_obj.elements["action"]))
            form_action.value="save_rename_search";

        form_obj.submit();
    }
}

function copy_rename_search(do_copy)
{
    var form_obj=$("copy_rename");
    if (form_obj && form_obj.elements)
    {
        var form_action;
        if ((form_action=form_obj.elements["copy_search"]))
            form_action.value=do_copy;
        form_obj.submit();
    }
}

function select_all_text(obj)
{
    var html_obj;
    if ((html_obj=$(obj)))
    {
        if (html_obj.createTextRange)
        {

            var range = html_obj.createTextRange();
            range.collapse(true);
            range.moveEnd('character', html_obj.value.length);
            range.moveStart('character', 0);
            range.select();
        }
        else
        {
            html_obj.setSelectionRange(0, html_obj.value.length);
        }
    }
}

function setCollaboration(search_id)
{
    var list_name = 'share' + search_id;
    var index = document.forms['searches'].elements[list_name].selectedIndex;
    var value = document.forms['searches'].elements[list_name].options[index].value;
    var url = 'saved_searches/';
    var arguments = 'set_shared&search_id=' + search_id + '&share_type=' + value;

    url+= '#' + search_id;

    var ok_callback = function()
                      {
                          $("updating_"+search_id).innerHTML = "Updated";
                          var search_anchor = $( "saved_search_" + search_id );
                          if ( search_anchor && search_anchor.firstChild )
                          { show_message("info", collaboration_options_changed, search_anchor.firstChild.nodeValue + changed_to_saved_search); }
                      };
                        
    var error_callback = function() { document.forms['searches'].submit(); };

    new Ajax.Request(url, { onSuccess: ok_callback,
                             onFailure: error_callback,
                             method: "post",
                             parameters:  arguments } );
    $("updating_"+search_id).innerHTML= "Updating...";    
}

function setEmailAlert(search_id,redirect_to_profile)
{
    var list_name = 'alert' + search_id;
    var index = document.forms['searches'].elements[list_name].selectedIndex;
    var value = document.forms['searches'].elements[list_name].options[index].value;
    var url = 'saved_searches/';
    var arguments = 'set_alert&search_id=' + search_id + '&interval=' + value;

    url+= '#' + search_id;
    var ok_callback = function()
                       {
                            //$("updating_"+search_id).update("Updated"); removed due a request #324862 attask
                            var search_anchor = $( "saved_search_" + search_id );
                            if ( search_anchor && search_anchor.firstChild )
                            { show_message("info", alert_state_changed, search_anchor.firstChild.nodeValue + changed_to_saved_search); }
                       };
                                        
    var error_callback = function() { document.forms['searches'].submit(); };
    
    new Ajax.Request(url, { onSuccess: ok_callback,
                             onFailure: error_callback,
                             method: "post",
                             parameters:  arguments } );
    //$("updating_"+search_id).update("Updating...");  removed due a request #324862 attask 
}

d= decodeURI;

//now that Firebug exists, pass though to that
function debug(text) {
    if (typeof console=='object' && typeof console.log=='function')
        console.log(text);
}

/* Sidebar Functions */

function scroll_win()
{
    var tip_container = $('tipContainer');
    
    if(tip_container && tip_container.style.display == 'block')
    {   
        if(window.innerHeight)
        {
            pos = window.pageYOffset
        }
        else if (document.documentElement && document.documentElement.scrollTop)
        {
            pos = document.documentElement.scrollTop
        }
        else if (document.body)
        {
            pos = document.body.scrollTop
        }

        var ifOpen = 0;
        if($('tipContentContainer').style.display == 'block')
        {  
            ifOpen = 180;  
        }         
        
        var tip_top = (Number($('currentPos').value.replace(/px/ig, "")) - ifOpen) + pos;
        var tip_height = Number(tip_container.style.height.replace(/px/ig, ""));
        var tip_bottom = tip_top + tip_height;
        var body_height = document.getElementsByTagName("body")[0].scrollHeight;
        var html_height = document.getElementsByTagName("html")[0].scrollHeight;
        var scroll_height = (body_height < html_height - 10) ? html_height - 10 : body_height;

        if (tip_bottom > scroll_height)
        {
          tip_top = scroll_height - tip_height;
        }
        
        if (tip_top < 200)
        {
            tip_top = 200;
        }
        
        tip_container.style.top = tip_top + "px";
    }
}

function scrollwin_cbk()
{
    if (!Prototype.Browser.WebKit)
    {
        hideTipContainer();
    }
    if (!animTimer) scrollwin(false);
}

function getPreference(cookiefield)
{
    var cookie = readCookie("GNPDUserPreferences");
    if(cookie != "")
    {
        var cookie_fields = new Array();
        cookie_fields = cookie.split("|");
        var length = cookie_fields.length;
        for(var i = 0 ; i < length ; ++i)
        {
            var current_field = new Array();
            current_field = cookie_fields[i].split("=");
            if (current_field.length == 2 && current_field[0] == cookiefield)
            {
                return current_field[1];
            }
        }
    }
    return "";
}

function setPreference(cookiefield, cookievalue)
{
    var today = new Date();
    today.setTime(today.getTime());
    var expires = new Date( today.getTime() + ( 60 * 1000 * 60 * 60 * 24));
    var cookie = readCookie("GNPDUserPreferences");
    var has_field = false;

    if(cookie != "")
    {
        var cookie_fields = new Array();
        cookie_fields = cookie.split("|");
        var length = cookie_fields.length;
        var i;
        for(i = 0 ; i < length ; ++i)
        {
            var current_field = new Array();
            current_field = cookie_fields[i].split("=");
            if (current_field.length == 2 && current_field[0] == cookiefield)
            {
                current_field[1] = cookievalue;
                cookie_fields[i] = current_field.join("=");
                has_field = true;
            }
        }
        if(!has_field)
        {
            var additional_field = new Array();
            additional_field[0] = cookiefield;
            additional_field[1] = cookievalue;
            cookie_fields[i] = additional_field.join("=");
        }
        cookie = cookie_fields.join("|");
    }

    document.cookie = "GNPDUserPreferences=" + cookie + ";expires=" + expires.toGMTString() + "; path=/";
}

function readCookie(cookieName) {
    var docCookies = document.cookie;
    var startIndex = docCookies.indexOf(cookieName);
    if (startIndex == -1) return false;
    startIndex += cookieName.length + 1;
    var endIndex = docCookies.indexOf(";",startIndex);
    if (endIndex == -1) endIndex = docCookies.length;
    var cookieValue = docCookies.substring(startIndex, endIndex);
    return unescape(cookieValue);
}

function show_message(msg_class, title, text)
{

    var mobj;
    var body_text = text;
    if ((mobj=$('jsolait_container')))
    {
        mobj.innerHTML = '';
    }
    if ((mobj=$("js_"+msg_class)))
    {

        var omsg;

        if ((omsg=$("pagecontent_subcontainer")))
        {
            omsg.className="show_msgs";
        }

        $("js_"+msg_class+"_title").innerHTML=title;

        mobj.style.display = "";

        if (arguments.length > 3)
        {
            var num_buttons = (arguments.length-3)/2;
            var btext = "<div class='msg_buttons'>";

            var button;
            for (button = 0; button < num_buttons; button++)
                btext = btext+"<a href=\""+arguments[4+(button*2)]+"\" class='msg_button'>"+arguments[3+(button*2)]+"</a>";

            btext += "</div>";

            body_text = body_text + btext;

        }

        $("js_"+msg_class+"_text").innerHTML=body_text;
        new Effect.ScrollTo($("js_"+msg_class+"_text").parentNode.parentNode);

        mobj.select("div")[0].show();
        restore_message(mobj.childNodes[0].id);

    }
}

function hide_message(msg_class)
{
    var tmp;
    if (arguments.length > 0)
    {
        if ((tmp=$("js_"+msg_class).childNodes[0]))
            $(tmp).hide();
    }
    else
    {
        if ((tmp=$("js_error").childNodes[0]))
            $(tmp).hide();

        if ((tmp=$("js_warning").childNodes[0]))
            $(tmp).hide();

        if ((tmp=$("js_info").childNodes[0]))
            $(tmp).hide();
    }
}

function minimise_message(id)
{
   var mmsg;
   if((mmsg = $(id)))
   {
       if (mmsg.className.substring(0,3) == "tt_" && mmsg.className.substring(0,8) != "tt_mini_")
       {
          mmsg.className = "tt_mini_" + mmsg.className.substring(3);
       }
   }
}

function restore_message(id)
{
   var mmsg;
   if((mmsg = $(id)))
   {
       if (mmsg.className.substring(0,8) == "tt_mini_")
       {
          mmsg.className = "tt_" + mmsg.className.substring(8);
       }
   }
}

/* This isn't sidebar stuff! It's for general use */

// prefer: http://www.prototypejs.org/api/element/addClassName
function addClassName(obj, name)
{
    $(obj).addClassName(name);
}

/**
 * obj - The dom element to change the classes of.
 * oldName - The class name to be replaced.
 * newName - The class name to replace the old one with.
 * ensureNewExists - Optional parameter that specifies
 *  that the new class name *must* be set, even if oldname was not
 *  present. Default is to not create the new classname if oldname
 *  was not found.
 */
function replaceClassName(obj, oldName, newName, ensureNewExists)
{
    obj=$(obj);
    if (ensureNewExists || obj.hasClassName(oldName))
    {
        obj.removeClassName(oldName);
        obj.addClassName(newName);
    }
}

//prefer: http://www.prototypejs.org/api/element/methods/removeClassName
function removeClassName(obj, name)
{
    $(obj).removeClassName(name);
}

function run_saved_search(formname)
{

    if (arguments.length == 0 || !document.forms[formname])
    {
        formname = "savedsearchform";
    }

    var obj;
    if ((obj=document.forms[formname]))
    {
        if((obj=document.forms[formname].elements["action"]))
            obj.value="run_search";
        if((obj=document.forms[formname].elements["search_id"]))
        {

            if(parseInt(obj.value) < 0)  //a heading, not a saved search
                return;

            window.location="/sinatra/gnpd/search&saved&id="+obj.value+"&exec/";
            return;
        }

    }

    show_message('error', "Could not run saved search" , "");
}

function edit_saved_search(formname)
{
    if (arguments.length == 0 || !document.forms[formname])
    {
        formname = "savedsearchform";
    }

    var obj;
    if ((obj=document.forms[formname]))
    {
        if((obj=document.forms[formname].elements["action"]))
            obj.value="edit_search";
        if((obj=document.forms[formname].elements["search_id"]))
        {

            if(parseInt(obj.value) < 0)  //a heading, not a saved search
                return;

            window.location="/sinatra/gnpd/search&saved&id="+obj.value+"/";
            return;
        }

    }

    show_message('error', "Could not edit saved search" , "");
}


/* Email validation*/

function check_email(mail_obj_id)
{
  $("js_error").hide();
    
  /*cm_error_title,cm_error_message    global variables provided for translation*/
  var obj=$(mail_obj_id);
  if(!obj||obj.value=="") return true;
  if(validate_email_string(obj.value))
  {
  return true;
  }
  else
  {
  show_message("error",cm_error_title,cm_error_message);  
  return false;
  }

}
/*End email validation*/ 

/* hopper management stuff */
get_scroll_pos = document.viewport.getScrollOffsets;

function confirm_hopper_leave(url, hopper_id)
{
  var pos = document.viewport.getScrollOffsets();
  var no_action = 'javascript:hide_message();window.scrollTo('+pos[0]+','+pos[1]+');';
  var yes_action = "javascript:jsolait_do_leave_hopper("+hopper_id+",'"+url+"');";
  show_message('warning', hh_msg_leave_title, hh_msg_leave_body, hh_msg_yes, yes_action, hh_msg_no, no_action);
}

function confirm_hopper_delete(url, hopper_id)
{
  var pos = document.viewport.getScrollOffsets();
  var no_action = 'javascript:hide_message();window.scrollTo('+pos[0]+','+pos[1]+');';
  var yes_action = "javascript:jsolait_do_delete_hopper("+hopper_id+",'"+url+"');";
  show_message('warning', hh_msg_delete_title, hh_msg_delete_body, hh_msg_yes, yes_action, hh_msg_no, no_action);
}

function confirm_delete(url, comment_id, item_id)
{
  var pos = document.viewport.getScrollOffsets();
  var no_action = 'javascript:hide_message();window.scrollTo(' + pos[0] + ',' + pos[1] + ');';
  var yes_action = "javascript:jsolait_do_delete_comment('" + comment_id + "','" + item_id + "','" + url + "')";
  show_message('warning', c_m_delete_comment, c_m_confirm_delete, c_m_yes, yes_action, c_m_no, no_action);
}

function comment_add (id, hopper_id, item_id)
{
  var form_div;
  if (id > 0)
  {
    form_div = document.getElementById('c_reply_' + id);
    if (!form_div)
    {
      return true;
    }
    if (form_div.className == 'comments_add')
    {
      hide_comment_add(id);
      form_div.className = '';
      return true;
    }
    if (form_div.className == 'comments_edit')
    {
      hide_comment_edit(id);
    }
  }
  else
  {
    form_div = $('hopper_' + hopper_id + '_item_' + item_id);
    if (!form_div)
    {
      return true;
    }
    if (form_div.className == 'comments_add')
    {
      form_div.className = '';
      form_div = $('hopper_hider');
    }
  }
  
  var divs = $$('div.comments_add');
  for (var i = 0; i < divs.length; ++i)
  {
      divs[i].className = '';
  }
    
  //do some W3C DOM magic
  form_div.className = 'comments_add';
  var the_form = $('hopper_add_holder');
  var parent = the_form.parentNode;
  parent.removeChild(the_form);
  form_div.appendChild(the_form);

  //update the hidden controls with the current values
  $('c_add_id').value = id;
  $('c_add_hopper_id').value = hopper_id;
  $('c_add_item_id').value = item_id;
  return true;
}

function hide_comment_add(id)
{
  var form_div = $('c_reply_'+id);
  var hider = $('hopper_hider');
  var the_form = $('hopper_add_holder');
  if (the_form.parentNode == form_div)
  {
    form_div.removeChild(the_form);
    hider.appendChild(the_form);
    form_div.className = '';
  }
  return true;
}

function hide_comment_edit(id)
{
  var form_div = $('c_reply_'+id);
  var hider = $('hopper_hider');
  var the_form = $('hopper_edit_holder');
  if (the_form.parentNode == form_div)
  {
    form_div.removeChild(the_form);
    hider.appendChild(the_form);
    form_div.className = '';
  }
  return true;
}

function hide_all_comment()
{
  var hider = $('hopper_hider');
  var add_form = $('hopper_add_holder');
  var editform = $('hopper_edit_holder');
  add_form.parentNode.removeChild(add_form);
  editform.parentNode.removeChild(editform);
  hider.appendChild(add_form);
  hider.appendChild(editform);
  
  var divs = $$('div.comments_edit', 'div.comments_add');
  for (var i = 0; i < divs.length; ++i)
  {
      divs[i].className = '';
  }
  
  return true;
}

function comment_edit(id, hopper_id, item_id)
{
  var form_div = $('c_reply_' + id);
  var body_src = $('comment_val_' + id);
  if (!form_div)
  {
    return true;
  }
  if (form_div.className == 'comments_edit')
  {
    hide_comment_edit(id);
    form_div.className = '';
    return true;
  }
  if (form_div.className == 'comments_add')
  {
    hide_comment_add(id);
  }

  var divs = $$('div.comments_edit');
  for (var i = 0; i < divs.length; ++i)
      divs[i].className = '';
  
  //do some W3C DOM magic
  form_div.className = 'comments_edit';
  var the_form = $('hopper_edit_holder');
  var parent = the_form.parentNode;
  parent.removeChild(the_form);
  form_div.appendChild(the_form);

  //update the hidden controls with the current values
  $('c_edit_id').value = id;
  $('c_edit_hopper_id').value = hopper_id;
  $('c_edit_item_id').value = item_id;
  $('c_edit_comment').value = body_src.innerHTML;
  return true;
}
/* End of hopper js */

function toggle_details(property)
{
   if ($(property + "_body").style.display != "none")
   {
      $(property + "_body").hide();
      $(property + "_toggle").src = "/gnpd/images/chevron_down.gif";
      $(property + "_heading").style.backgroundImage = "url(/gnpd/images/big_arrow.gif)";
   }
   else
   {
      $(property + "_body").show();
      $(property + "_toggle").src = "/gnpd/images/chevron_up.gif";
      $(property + "_heading").style.backgroundImage = "url(/gnpd/images/big_arrow_down.gif)";                 
   }
}

function show_analysis()
{
    var a = parent.document.getElementById('fastfacts_iframe');
    var drop = parent.document.getElementById('fastfacts_dropzone');
    var topfives = $('container');
    if (!a || !drop || !topfives)
    {
        return;
    }
    drop.innerHTML = topfives.innerHTML;

    $(a).hide();
}

function validate_sso_password_change(frm)
{
    if (frm)
    {
        if (frm.password.value == frm.password1.value)
        {
            return true;
        }
        alert(msg_pass_dont_match);
    }
    return false;
}

function isClassName(obj, name)
{
    return $(obj) && $(obj).hasClassName(name);
}

function popup_submit_form(form_name, width, height, win_config)
{
    var frm;
    if ((frm=document.forms[form_name]))
    {
        window.open("", "win_"+form_name, "width=" + width + ",height=" + height + "," + win_config );
        frm.target="win_"+form_name;
        frm.submit();
    }    
}

/* START of some generic functions */
/* If class_2 is the empty string then the presence of class_1 is performed instead */
function toggleClassSingle (obj, class_1, class_2)
{
  var orig_class, new_class;
  // Find if the first tbody is visible or not, and then
  //  toggle that status
  if (isClassName(obj, class_1))
  {
    orig_class = class_1;
    new_class = class_2;
  }
  else
  {
    orig_class = class_2;
    new_class = class_1;
  }
  if (new_class=="")
    removeClassName(obj, orig_class);
  else if (orig_class=="")
    addClassName(obj, new_class);
  else
    replaceClassName(obj, orig_class, new_class, true);
}

/* @p method = true: Toggle each element in elements according to how the first element should be toggled
 * @p method = false: Toggle each element according to its own original status
 * If class_2 is the empty string then the presence of class_1 is performed instead */
function toggleClass (elements, method, class_1, class_2)
{
  // Find if the first element is visible or not, and then
  //  toggle that status
  var orig_class = undefined, new_class = undefined;
  for (var i = 0; i < elements.length; i++)
  {
    var cur_obj = elements[i];
    if (isUndefined(orig_class) || !method)
    {
      if (isClassName(cur_obj, class_1))
      {
        orig_class = class_1;
        new_class = class_2;
      }
      else
      {
        orig_class = class_2;
        new_class = class_1;
      }
    }
    if (new_class=="")
      removeClassName(cur_obj, orig_class);
    else if (orig_class=="")
      addClassName(cur_obj, new_class);
    else
      replaceClassName(cur_obj, orig_class, new_class, true);
  }
}

/**
 * Removes the nodes passed in the array @p nodes from the DOM to which they belong.
 */
function removeNodes(nodes)
{
    while (nodes.length > 0)
        $(nodes[0]).remove();
}

/* END of some generic functions */

/* START of generic expandable box code */
/* Toggles a div.expandable open and closed. @p obj is any element within the div.expandable element (or the div.expandable element itself) */
function expandableToggle (obj)
{
  // Find the <div class="expandable"> element
  var exp_obj;
  {
    var cur_obj = obj;
    while (true)
    {
      if (cur_obj.nodeType != 1)
        return;
      if (cur_obj.nodeName == "DIV"
        && isClassName(cur_obj, "expandable"))
      {
        exp_obj = cur_obj;
        break;
      }
      cur_obj = cur_obj.parentNode;
    }
  }
  // Toggle the classes
  toggleClassSingle(exp_obj, "closed", "");
}
/* END of generic expandable box code */

/* START of generic array filtering code */
var filter = {};

/**
 * Returns an array containing all the elements of the passed array for which the function criteria returns True.
 * @param[in] list The array of values.
 * @param[in] criteria A function that returns true or false, and accepts a single argument (each value of @p list in turn).
 * @return A new array containing those values from @p list for which @p criteria returned true. The order from the original array
 *  is respected.
 */
filter.filter = function (list, criteria)
{
    var listCopy = copyArray(list);
    var results = [];
    
    // Now apply the criteria to whittle down the list
    for (var i = 0; i < list.length; i++)
    {
        var value = list[i];
        if (criteria(value))
            results.push(value);
    }

    return results;
}

/* After this point are commonly useful filter functions which return a function object that is suitable for use in @p criteria value in filter.filter() */

/** Returns true for everything passed to it */
filter.fAll = function () { return function (value) { return true; } }
/** Returns false for everything passed to it */
filter.fNone = function () { return function (value) { return false; } }
filter.dom = {};
/** Returns true for DOM elements which have the given class name */
filter.dom.fClassName = function (className) { return function (value) { return isClassName(value, className); } }

/* END of generic array filtering code */

function addDebugIframe(obj)
{
    if (document.getElementById('pagefooter'))
        setDebugPosition(obj);
    else
        Event.observe(window, 'load', function() { setDebugPosition(obj) });
}

function setDebugPosition(obj)
{
    var initValue = obj.previousSibling.innerHTML.replace(/&gt;&lt;/ig, "&gt;\n&lt;");
    if(!document.getElementById('debugSection'))
    {
      var dContainer = document.createElement("div"); 
      if(navigator.appName == "Microsoft Internet Explorer")
      {      
         document.body.firstChild.appendChild(dContainer);         
      }
      else
      {  
             document.body.appendChild(dContainer);
      }
      dContainer.setAttribute("id", "debugSection");
      dContainer.style.position="absolute";
      dContainer.style.top= (document.getElementById('pagefooter').offsetTop + 20) + "px";
      dContainer.style.width="99%";      
      dContainer.innerHTML+=initValue;
    }
  else
  {
     document.getElementById('debugSection').innerHTML+=initValue;
  }  
}

var tipTime=null;

function setTipDelay()
{
    tipTime = setTimeout(clearTipDelay, 30000);
}

function clearTipDelay()
{
    clearTimeout(tipTime);
    hideTipContainer();
}

function setTipContainerPosition(set_delay, to_display)
{     
  
    if($("tipContainer"))
    { 
        if($('tipLink'))
        {
          $('tipLink').style.display='block';
            $('tipLink').style.visibility = 'hidden';    
        }
  
        var viewportwidth;
        var viewportheight; 
   
        if (typeof window.innerWidth != 'undefined')
        {
            viewportwidth = window.innerWidth,
             viewportheight = window.innerHeight      
        }
        else if (typeof document.documentElement != 'undefined'
            && typeof document.documentElement.clientWidth !=
            'undefined' && document.documentElement.clientWidth != 0)
        {
            viewportwidth = document.documentElement.clientWidth,
            viewportheight = document.documentElement.clientHeight
        } 
        else
        {
            viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
            viewportheight = document.getElementsByTagName('body')[0].clientHeight
        }
   
        var decrementor="";
        if(navigator.appName == "Microsoft Internet Explorer")
        {      
            decrementor = 6;         
        }
        else
        {  
            decrementor = 21;
        }
        var tip = $("tipContainer");    
        var containerHeight = tip.style.height.match(/\d*/g);
        var containerWidth = tip.style.width.match(/\d*/g);
      
      
        var topPosition = viewportheight - containerHeight[0] - 5;
        var leftPosition = viewportwidth - containerWidth[0] - decrementor;
      
        var ifOpen=0;
  
        if($('tipContentContainer').style.display == 'block')
        {      
            ifOpen = 180;                 
        }     
              
        if (leftPosition < 200)
        {
            leftPosition = 200;
        }
        var tipIframe = $("tip_iframe"); 
        
        tip.style.top = (topPosition + ifOpen) + "px";
        tip.style.left = leftPosition + "px";
        
        if(tipIframe)
        {
          tipIframe.style.top = tip.style.top; 
          tipIframe.style.left = tip.style.left;
        }  
        $("currentPos").value = tip.style.top;            
        
        if (to_display)
        {
            tip.style.display = 'block';
            if(tipIframe)
           {
              tipIframe.style.display = 'block';
           }
            if(set_delay)
            {
                setTipDelay();
            }
        }
        else
        {
            hideTipContainer();
        }
      
        scroll_win();
    }
}

function hideTipContainer()
{
    var tipContainer = $('tipContainer');
    if(tipContainer)
    {
        var tipIframe = $('tip_iframe');
        $('tipContentContainer').hide();
    
        if(Number(tipContainer.style.height.replace(/px/ig, "")) > 130)
        {
            tipContainer.style.height = (Number(tipContainer.style.height.replace(/px/ig, "")) - 180) + "px";
            if(tipIframe)
            {
              tipIframe.style.top = tipContainer.style.top; 
              tipIframe.style.left = tipContainer.style.left;
              tipIframe.style.height = tipContainer.style.height;      
            }
        }  
        tipContainer.hide();
        if(tipIframe)
            tipIframe.hide();
        
        if($('tipLink'))
        {
             $('tipLink').style.visibility = "visible"; 
        }
      
        clearTimeout(tipTime);
    }
}

function setReadMoreTip(reqUrl)
{  
    new Ajax.Request(reqUrl);
}  

function showTipDetails(obj)
{  
  clearTimeout(tipTime);  
  setReadMoreTip($('readMoreLink').value);    
  var container = $('tipContainer');
  var tipIframe = $('tip_iframe');
    
  if(obj.nextSibling.style.display == 'none')
  {
        container.style.height = Number(container.style.height.replace(/px/ig, ""))+ 180 + "px";        
        container.style.top = Number(container.style.top.replace(/px/ig, "")) - 180 + "px";
      
      if(tipIframe)
        {
      tipIframe.style.height = container.style.height;      
      tipIframe.style.top = container.style.top;
        }
      obj.nextSibling.style.display = 'block';
  }
  else
  {
    container.style.height = Number(container.style.height.replace(/px/ig, ""))- 180 + "px";
    container.style.top = Number(container.style.top.replace(/px/ig, "")) + 180 + "px";
    
    if(tipIframe)
  {
      tipIframe.style.height = container.style.height;      
    tipIframe.style.top = container.style.top;
  }
    obj.nextSibling.style.display = 'none';
    setTipDelay();
  }
}

function hideAllHelpTopics(obj, name, frame_name)
{
    var topics = getElementsByName_iefix("div", name);

    for(i=0;i<topics.length;i++)
    {
        if (!obj || topics[i].id != obj.nextSibling.id)
        {
            $(topics[i].id).hide();
        }
    }
}

function getAbsoluteOffsetTop(obj)
{
  var parent = obj.parentNode;
    var offset_top = (obj.offsetTop) ? obj.offsetTop : 0;
  if (parent)
  {
    return offset_top + getAbsoluteOffsetTop(parent);
  }
  return offset_top;
}

function neverDisplayTip(id)
{
    $('tipContainer').hide();
    $('tip_iframe').hide();
    $('tipLink').style.visibility = "hidden";
        
    var url = "/sinatra/gnpd/help/action=disable&group=" + id;    
    new Ajax.Request(url, {  method: 'post' } );
}

function decToHex(num)
{
    var hexNums = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "A", "B", "C", "D", "E", "F"); 
    var hex = "";
    while (num >= 16)
    {
        temp = num % 16;
        num = Math.floor(num / 16);
        hex += hexNums[temp];
    }
    hex += hexNums[num];
    
    var hexRev = "";
    var len = hex.length;
    for (var i = 0; i < len; i++)
        hexRev = hexRev + hex.substring(len-i-1, len-i); 
    return hexRev; 
} 

function encode_win1252(originalVal)
{
    var encodedVal = "";
    for (var i=0; i < originalVal.length; i++)
    {
        if (originalVal.substring(i,i+1).charCodeAt(0) < 255)
        {
            var checkChar = originalVal.substring(i,i+1)
            if (checkChar.charCodeAt(0) > 32 && checkChar.charCodeAt(0) < 123 && "\"<>%\\^[]`\+\$\,".indexOf(checkChar) == -1)
                encodedVal = encodedVal + checkChar;
            else
                encodedVal = encodedVal + "%" + decToHex(checkChar.charCodeAt(0));
        }
    }
    return encodedVal;    
}
