





























//Global array of functions to be called ondomready
var WishpotOnDomReadyFunctions = [];

/******************************************
 Common DOM Wrappers (FB + Regular DOM)
******************************************/
var WPJS = {
  CheckBoxGetChecked: function(cb){
    return cb.checked;
  },
  
  CheckBoxSetChecked: function(cb, value){
    cb.checked = value;
  },
  
  //Alert box with "Ok" button.  Title ignored for non-facebook apps.
  Alert: function(msg){
    return alert(msg);
  },
  
  AlertWithTitle: function(msg, title, timeout){
    var newdiv = document.createElement('div');
    WPJS.SetInnerXHTML(newdiv, msg);
    return WPJS._OpenAlertDialog(title, newdiv, null, timeout);
  },
  
  SetStyle: function(obj, name, value){
    obj.style[name] = value;
  },
  
  GetStyle: function(obj, name){
    return obj.style[name];
  },
  
  SetClass: function(obj, value){
    obj.className = value;
  },
  
  GetClass: function(obj){
    return obj.className;
  },
  
  //for select boxes
  GetSelectedIndex: function(obj){
    return obj.selectedIndex;
  },
  
  GetOptions: function(obj){
    return obj.options;
  },
  
  ClearOptions: function(select){
    while(select.options.length > 0)
    {
        select.remove(0);
    }
  },  
 
  CreateOption: function(name, value){
    return new Option(name, value);
  },
  
  AddOption: function(select, option){
    var options = select.options;
	options[options.length] = option;
  },
  
  //should work on any form element
  GetValue: function(select){
    return select.value;
  },
  
  //should work on any form element
  SetValue: function(obj, newValue){
    return obj.value = newValue;
  },
  
  //facebook requires full XHTML
  SetInnerXHTML: function(obj, text){
    obj.innerHTML = text;
  },
  
  SetSelected: function(obj, newValue){
    return obj.selected = newValue;
  },
  
  GetSelected: function(obj){
    return obj.selected;
  },
  
  SetDisabled: function(obj, newValue){
    return obj.disabled = newValue;
  },
  
  GetDisabled: function(obj){
    return obj.disabled;
  },
  
  GetClientWidth: function(obj){
    return obj.clientWidth;
  },
  
  GetClientHeight: function(obj){
    return obj.clientHeight;
  },
  
  GoTo: function(url){
    window.location = url;
  },
  
  GetParentNode: function(obj){
    return obj.parentNode;
  },
  
  GetFirstChild: function(obj){
    return obj.firstChild;
  },
  
  GoToNewWindow: function(url, windowName, js_options){
    window.open(url, windowName, js_options);
  },
  
  AddClass: function(obj, className){
    WithJQuery(function(){
        $(obj).addClass(className);
    });
  },
  
  RunOnDomReady: function(func){
    WishpotOnDomReadyFunctions.push(func);
  },
  
  _OpenAlertDialog: function(title, div_obj, width, auto_close_ms){
    WithJQueryUi(function(){
          var diag = jQuery(div_obj);
          if(typeof(width) == "undefined"){ width = 400; }
          diag.dialog({modal: true, autoOpen: false, title: title, width: width});
          diag.show();
          diag.dialog('open');
          if(typeof(auto_close_ms) != "undefined")
          {
            setTimeout(function(){diag.dialog('close');}, auto_close_ms);
          }        
          return diag;
      });
  },
  
  //Turns a div into a dismissable modal window
  AlertDialogDiv: function(title, div_id, width){
    return WPJS._OpenAlertDialog(title, document.getElementById(div_id), width);
  },
  
  _OpenConfirmationDialog: function(title, div_obj, onsuccesscallback){
      WithJQueryUi(function(){
          var diag = jQuery(div_obj);
          diag.show();
          diag.dialog({modal: true, 
            autoOpen: false, 
            title: title,
            buttons: {
              Cancel: function() {
                $(this).dialog('close');
              },
              Ok: function(){
                onsuccesscallback();
                $(this).dialog('close');
              }
           }
          });
          diag.dialog('open');
          return diag;
        });
  },
  
  //Creates a dialog out of an existing div
  ConfirmationDialogDiv: function(title, div_id, onsuccesscallback){
    var div = document.getElementById(div_id);
    WPJS._OpenConfirmationDialog(title, div, onsuccesscallback);
  },
  
  ConfirmationDialog: function(title, message, onsuccesscallback){
    var newdiv = document.createElement('div');
    WPJS.SetInnerXHTML(newdiv, message);
    WPJS._OpenConfirmationDialog(title, newdiv, onsuccesscallback); 
  }
  
}

/******************************************
Common
******************************************/



document.getElementsByClassName = function(cl) {
var retnode = [];
var myclass = new RegExp('\\b'+cl+'\\b');
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) retnode.push(elem[i]);
}
return retnode;
}; 

//left in for backward-compatibility.  Eventually remove.
function GoTo(url) {  WPJS.GoTo(url); }

function FormatReturnUrl()
{
    var ruArg = 'ru=' + encodeURIComponent(window.location);
    return ruArg;
}

function DummyFunction() { return; }

function HitUrl(url)
{
	var i=new Image(1,1);
	i.src=url;
	i.onload=function() {DummyFunction();}
}

var last_err = null;
function ReportError(err, url, line)
{
	try
	{
	    if(err == last_err && err != null){return true;}
	    last_err = err;
	    var msg = "" + err;
	    var err_url = window.location.href;
	    if (url != null) err_url = url;
	    var err_line = ""+line;
	    var url = "/cerr.aspx?msg=" + encodeURIComponent(msg) + "&url=" + encodeURIComponent(err_url) + "&line=" + err_line + "&stack=" + encodeURIComponent(stacktrace());
		HitUrl(url);
	}
	catch(ex2)
	{}
	
	//supress the eventual javascript error
    return true;
}


function AsyncErrHandler(ex, url, line)
{
	try{ ReportError(ex, url, line); }
	catch(ex2){}

	try{ alert("The asynchronous operation failed. Please try again later. \n["+ex+"]"); }
	catch(ex2){}
}

function JqueryAjaxErrHandler(XMLHttpRequest, textStatus, errorThrown) 
{
  return AsyncErrHandler(textStatus, window.location.href, errorThrown);
}

// This function returns a string that contains a "stack trace."
// FROM: http://examples.oreilly.com/jscript3/text/7-3.txt
function stacktrace() {
    var s = "";  // This is the string we'll return.
    //alert(stacktrace.caller.toString());
    // Loop through the stack of functions, using the caller property of
    // one arguments object to refer to the next arguments object on the
    // stack.
    try {
        for (var a = stacktrace.caller; a != null; a = a.caller) {
            // Add the name of the current function to the return value.
            s += funcname(a) + " <-- ";

            // Because of a bug in Navigator 4.0, we need this line to break.
            // a.caller will equal a rather than null when we reach the end 
            // of the stack. The following line works around this.
            if (a.caller == a) break;
        }
    } catch (ex) {
        //silent catch - in case we have no permission
    }
    return s;
}
// This function returns the name of a given function. It does this by
// converting the function to a string, then using a regular expression
// to extract the function name from the resulting code.
function funcname(f) {
    if (f == null) return "null?";
    var s = f.toString().match(/function (\w*)/)[1];
    if ((s == null) || (s.length == 0)) return "anonymous";
    return s + " (" + f.arguments + ")";
}


// Enable global error handling
window.onerror = function(err, url, line) {
    //skip errors that are not worth reporting
    var errstr = "";
    if(err != null) errstr = ""+err;
    if(errstr.indexOf("openx") >= 0 || errstr.indexOf("GA_google") >= 0 || errstr.indexOf("GS_google") >= 0 || errstr.indexOf("doubleclick") >=0 || errstr.indexOf("Error loading script") >=0) return true;
    return ReportError(err, url, line);
}

//Give the id of an image object, set it's source to the provided url
function SetImgSrc(imgId, url) {
    var i = document.getElementById(imgId);
    if (null != i) i.src = url;
}

/****************************
 JQuery loading
 ****************************/
var g_JqueryPresent = false;
var g_MaxJqueryAttempts = 30;

function jQueryLoaded(){  return (typeof(jQuery) != "undefined"); }
function jQueryUiLoaded(){ return (jQueryLoaded() && typeof(jQuery.ui) != "undefined")}

function WithJQuery(fn, attempt_num)
{
	if(jQueryLoaded())
	{
	    try{ fn(); }
	    catch(ex) { AsyncErrHandler(ex); }
	}
	else
	{
	    if(!attempt_num) { attempt_num = 1; }
	    else { attempt_num+=1; }
	    
	    if(attempt_num > g_MaxJqueryAttempts)
	    {
	        alert("Sorry, we were unable to load the necessary libraries to complete this operation.  Please try again, and if the problem continues, contact us.");
	        throw "Error loading JQuery after "+attempt_num+" tries.";
	    }
	    else { setTimeout(function(){WithJQuery(fn, attempt_num)}, 1000); }
	}
}

function WithJQueryUi(fn, attempt_num)
{
	if(jQueryUiLoaded())
	{
	    try{ fn(); }
	    catch(ex) { AsyncErrHandler(ex); }
	}
	else
	{
	    if(!attempt_num) { attempt_num = 1; }
	    else { attempt_num+=1; }
	    
	    if(attempt_num > g_MaxJqueryAttempts)
	    {
	        alert("Sorry, we were unable to load the necessary libraries to complete this operation.  Please try again, and if the problem continues, contact us.");
	        throw "Error loading JQuery UI after "+attempt_num+" tries.";
	    }
	    else { setTimeout(function(){WithJQueryUi(fn, attempt_num)}, 1000); }
	}
}

function CloseDialog(id)
{
  WithJQueryUi(function(){
    var diag = $('#'+id);
    diag.dialog();
    diag.dialog('close');
  });
}

/******************************************
Ext loading support
******************************************/

var g_ExtLoadIssued=false;
var g_ExtLoadCompleted=false;

function SetExtLoadIssued(v)
{
	g_ExtLoadIssued=v;
}
function SetExtLoadCompleted(v)
{
	if(v)
	{
		var s = document.getElementById("ExtCssSrc").innerHTML;
		var style = document.getElementById("ExtCss");

		if(style.styleSheet){// IE
			style.styleSheet.cssText = s;
		} else {// w3c
			var cssText = document.createTextNode(s);
			style.appendChild(cssText);

		}
	}
	g_ExtLoadCompleted=v;
}
function GetExtLoadIssued()
{
	return g_ExtLoadIssued;
}
function GetExtLoadCompleted()
{
	return g_ExtLoadCompleted;
}

function WithExtFull(fn)
{
	if(GetExtLoadCompleted())
	{
		try
		{
			fn();
		}
		catch(ex)
		{
			AsyncErrHandler(ex);
		}
	}
	else
	{
		var el = Ext.get("ext-part2");
		var upd = el.getUpdateManager();
		
		if(GetExtLoadIssued())
		{
			upd.on("update", function(e,t) { SetExtLoadCompleted(true); fn(); });
		}
		else
		{
			SetExtLoadIssued(true);
			upd.showLoadIndicator = false;
			upd.on("failure", function(e,t) { SetExtLoadIssued(false); SetExtLoadCompleted(false); AsyncErrHandler("Ext load failed"); });
			upd.on("update", function(e,t) { SetExtLoadCompleted(true); fn(); });

			upd.update({ 
				url: "/lib/ext/2.1/ext-part2.htc",
				scripts: true,
				timeout: 30
			});
		}
	}
}

function BeginLoadExtFull()
{
	WithExtFull(function() {});
}


/******************************************
NavTab
******************************************/

function TabOn(el)
{
	if(el.className == 'inactiveTab')
		el.className = 'inactiveTabHover';
	else if(el.className == 'activeTabC')
		el.className = 'activeTabCHover';
}
function TabOff(el)
{
	if(el.className == 'inactiveTabHover')
		el.className = 'inactiveTab';
	else if(el.className == 'activeTabCHover')
		el.className = 'activeTabC';
}

function SearchOn(el)
{
	if(el.className == 'searchOff')
		el.className = 'searchOn';
}
function SearchOff(el)
{
	if(el.className == 'searchOn')
		el.className = 'searchOff';
}

function BtnOn(el)
{
	if(el.className == 'blink')
		el.className = 'blinkHov';
	else if(el.className == 'link')
		el.className = 'linkHov';
}
function BtnOff(el)
{
	if(el.className == 'blinkHov')
		el.className = 'blink';
	else if(el.className == 'linkHov')
		el.className = 'link';
}

/******************************************
DateTime
******************************************/


function FormatDateTime(msecs, includeTime) 
{
	d = new Date();

	//localOffset = d.getTimezoneOffset() * 60000;
	localTime = msecs; // + localOffset;
        d.setTime(localTime);

	res = (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getFullYear();

	if(includeTime)
	{
		h = d.getHours();
        m = d.getMinutes();

        ampm = "AM";
        if(h > 11)
        {
	   		h = h - 12;
           	ampm = "PM";
        }
        if(h == 0)
           	h = 12;
        
        if(m < 10)
            ms = "0" + m;
        else
            ms = m.toString();

		res = res + " at " + h + ":" + ms + " " + ampm;
	}
	return res;
}


/******************************************
User
******************************************/

function GoFindUser(sk)
{
    GoTo("/public/users/find.aspx?sk=" + sk);
}



function GoDeleteFriend(uid)
{
    if(confirm('Are you sure you want to remove this friend?'))
    {
        GoTo("/my/actions.aspx?action=deletefriend&uid=" + uid);
    }
}

/******************************************
Amazon lists
******************************************/
function Trim(s)
{
    return s.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function GoImportList(el)
{
    var parentForm = FindParentForm(el);
    if(parentForm)
    {
        if(parentForm.CreateNewList.value.toLowerCase() == "true")
        {
            var listName = parentForm.ListName.value;
            if(Trim(listName) == '')
            {
                alert('Please enter a name for the new list');
                return false;
            }
        }

        if(confirm('All the new items in this list will be imported. Are you sure you want to continue?'))
        {
		    SubmitForm(parentForm);
        }
    }
}


/******************************************
Wish
******************************************/

function SetWish(wid,action)
{
    document.getElementById('WishIdInput').value=wid;
    document.getElementById('WishActionInput').value=action;
}
function ConfirmDeleteWish(url)
{
    if(confirm('Are you sure you want to delete this item?'))
    {
	GoTo(url);
    }
}
function GoArchiveWish(wid)
{
	GoTo("/my/actions.aspx?action=setstatus&status=purchased&wid=" + wid + "&" + FormatReturnUrl());
}
function GoUnarchiveWish(wid)
{
	GoTo("/my/actions.aspx?action=setstatus&status=unpurchased&wid=" + wid + "&" + FormatReturnUrl());
}
function GoDeleteWishComment(wid,cid)
{
    if(confirm('Are you sure you want to delete this comment?'))
    {
	GoTo("/my/actions.aspx?action=deletecomment&wid=" + wid + "&cid=" + cid);
    }
}
function GoFlagWishComment(wid,cid)
{
    if(confirm('Are you sure you want to mark this comment as spam and delete it?'))
    {
	GoTo("/my/actions.aspx?action=flaganddeletecomment&wid=" + wid + "&cid=" + cid);
    }
}

function JumpToPage()
{
    var baseUrl = document.getElementById('PagerBaseUrl').value;
    var page = document.getElementById('JumpToPageInput').value;
    window.location = baseUrl + page;
}

function SortChange()
{
    var baseUrl = document.getElementById('SorterBaseUrl').value;
    var sortValue = document.getElementById('SortSelect').value;
    GoTo(baseUrl + sortValue);
}

function WishStatusSelectionChange()
{
    var baseUrl = document.getElementById('WishStatusSelectorBaseUrl').value;
    var sortValue = document.getElementById('WishStatusSelectorSelect').value;
    GoTo(baseUrl + sortValue);
}

/*** Search tip ***/

function SearchBoxFocus(tb)
{
	if(tb.className != "searchBoxTip")
		return;

	tb.value = "";
	tb.className = "searchBox";
}

function ValidateSearch(tbid)
{
	var tb = document.getElementById(tbid);
	return(tb.className != "searchBoxTip");
}

//Deprecated... use ToggleBlockDisplay in wishpot_common instead.
function ToggleDisplay(id)
{
	var div = document.getElementById(id);
	if(div.style.display == "block")
		div.style.display = "none";
	else
		div.style.display = "block";
}

function ToggleDisplayAndFocus(id, focusEl)
{
    ToggleDisplay(id);

	var div = document.getElementById(id);
	if(div.style.display == "block")
        document.getElementById(focusEl).focus();
}

function SwitchDisplay(idShow, idHide)
{
	document.getElementById(idShow).style.display = "block";
	document.getElementById(idHide).style.display = "none";
}

function SetOff(el)
{
	var cl = el.className;
	if(cl)
	{
		var pos = cl.indexOf(" on");
		if(pos >= 0 && (pos == cl.length-3))
			el.className = cl.substring(0, pos) + " off";
	}
}
function SetOn(el)
{
	var cl = el.className;
	if(cl)
	{
		var pos = el.className.indexOf(" off");
		if(pos >= 0 && (pos == cl.length-4))
			el.className = cl.substring(0, pos) + " on";
	}
}

function OpenReserveDialog(id, murl, mname)
{
	WithExtFull(function(){
		var winId = "win_" + id;
		var win = Ext.getCmp(winId);
		if(win)
		{
			win.close();
		}

		var x = Ext.getDom(id);
		if(murl)
		{
			x = x.cloneNode(true);
			var wel = new Ext.Element(x, true);
			wel.child(".forReserve").replaceClass("forReserve", "forBuy");
			wel.child("input.__murl", true).value = murl;
			wel.child("input.__mname", true).value = mname;
			wel.child("a.__murl", true).href = murl;
			x = wel.dom;
		}
		
		var html = x.innerHTML;
		win = new Ext.Window({
			id:winId,
			html:html,
			//title:'Please reserve this gift before buying',
			layout:'fit',
			width:500,
			height:'auto',
			constrain:true,
			modal:true,
			resizable:false,
			plain:false
		});

		win.show();
	}); 
}

function OpenDialog(id)
{
	WithExtFull(function(){
		var winId = "win_" + id;
		var win = Ext.getCmp(winId);
		if(win)
		{
			win.close();
		}

		var x = Ext.getDom(id);
		if (null == x) {
		    throw ("Tried to open a dialog with an id of " + id + " but no element was found");
		}	
		var html = x.innerHTML;
		win = new Ext.Window({
			id:winId,
			html:html,
			layout:'fit',
			width:500,
			height:'auto',
			constrain:true,
			modal:true,
			resizable:false,
			plain:false
		});

		win.show();
	}); 
}

function BeginBuy(uid, wid, pid) {
    var url = '/ajax/bestoffer.aspx?uid=' + uid + '&wid=' + wid + '&pid=' + pid;
    var callback = function(data) { EndBuy(data, wid); }
    jQuery.ajax({ data: '', error: JqueryAjaxErrHandler, success: callback, type: "GET", dataType: 'json', url: url });
}
	
function EndBuy(data,wid) {
    OpenReserveDialog("popRes_" + wid, data.MerchantUrl, data.MerchantName);
}


function ToggleAltPicPicker(id, altClass)
{
	SetAltThumbStyles(-1);
	
	var id = "AltPicPicker";
	var altClass = "AltPicPickerToggle";
	var textId = "AltPicPickerText";
	var el = document.getElementById(id);
	var tel = document.getElementById(textId);
	var altEls = ((altClass != null) ? document.getElementsByClassName(altClass) : null);
	if(el.style.display == "block")
	{
		el.style.display = "none";
		tel.innerHTML = "see more pictures";
		tel.style.visibility = "visible";
		for(var i = 0; i < altEls.length; i++)
			altEls[i].style.visibility = "visible";
	}
	else
	{
		el.style.display = "block";
		tel.innerHTML = "see item details";
		for(var i = 0; i < altEls.length; i++)
			altEls[i].style.visibility = "hidden";
	}
}

function GetPrefAltPic()
{
	return (document.getElementById("PrefPic").value * 1);
}
function SetPrefAltPic(idx)
{
	document.getElementById("PrefPic").value = idx;
}
function GetAltPicCount()
{
	return (document.getElementById("PicCount").value * 1);
}
function GetAltPicEl(idx)
{
	return document.getElementById("AltPic"+idx);
}
function GetAltThumbEl(idx)
{
	return document.getElementById("AltThumb"+idx);
}
function SetAltPic(idx)
{
	var picCount = GetAltPicCount();
	for(var i=0; i<picCount; i++)
	{
		var el = GetAltPicEl(i);
		if(i == idx)
			el.style.display = "block";
		else
			el.style.display = "none";
	}
}
function SetAltThumbStyles(tempSel)
{
	var picCount = GetAltPicCount();
	var pref = GetPrefAltPic();
	for(var i=0; i<picCount; i++)
	{
		var el = GetAltThumbEl(i);
		if(i == pref)
			el.className = "SelAltThumb";
		else if(i == tempSel)
			el.className = "TempSelAltThumb";
		else
			el.className = "AltThumb";
	}
}
function AltThumbMouseOver(idx)
{
	var pref = GetPrefAltPic();
	if(pref != idx)
	{
		var el = GetAltThumbEl(idx);
		el.className = "TempSelAltThumb";
	}
	SetAltPic(idx);
	document.getElementById("AltPicPickerText").style.visibility = "hidden";
}

function AltThumbMouseOut(idx)
{
	var pref = GetPrefAltPic();
	if(pref != idx)
	{
		var el = GetAltThumbEl(idx);
		el.className = "AltThumb";
	}
	SetAltPic(pref);
	document.getElementById("AltPicPickerText").style.visibility = "visible";
}
function AltThumbClick(idx)
{
	SetAltPic(idx);
	SetPrefAltPic(idx);
	ToggleAltPicPicker();
}

function GoResendVerificationMail()
{
    GoTo("/my/actions.aspx?action=resendmail");
}

function FindParentForm(el)
{
	while(el && (el.nodeName.toLowerCase() != "form"))
		el = el.parentNode;
		
	return el;
}

function SubmitForm(el)
{
    var form = FindParentForm(el);
    
	if(form)
		form.submit();
}

function IEVer()
{
      var ua = window.navigator.userAgent;
      var msie = ua.indexOf ("MSIE ");

      if (msie > 0)     
         return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )));
      else                 
         return 0;
}

/** Messaging **/
function SetAction(element, action, confirmText)
{
    if(confirmText != null && confirmText.length > 0) 
    {
        if(!confirm(confirmText)) 
        {
            return false;
        } 
    }
    
    document.getElementById("Action").value = action;
    SubmitForm(element);
    return true;
}

function UpdateEveryoneChkBox() 
{
    var friendsChkBox = document.getElementById("AcceptFromFriendsInput");
    var everyoneChkBox = document.getElementById("AcceptFromEveryoneInput");
    
    if(!friendsChkBox.checked) 
    {
        everyoneChkBox.checked = false;
    }
    
    return true;
}

function UpdateFriendsChkBox()
{
    var friendsChkBox = document.getElementById("AcceptFromFriendsInput");
    var everyoneChkBox = document.getElementById("AcceptFromEveryoneInput");

    if(everyoneChkBox.checked) 
    {
        friendsChkBox.checked = true;
    }
    
    return true;
}

function AddEmailIfEnter(e)
{
    var keynum

    if(window.event) // IE
    {
        keynum = e.keyCode
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which
    }

    if(keynum == 13)
    {
        AddEmail();
    }
}

function AddEmail() 
{
    var targetElement = document.getElementById('EmailsHidden');
    var sourceElement = document.getElementById('EmailInput');
    var toDiv = document.getElementById('ToDiv');
    
    targetElement.value += sourceElement.value + ";";
    sourceElement.value = "";
    toDiv.innerHTML = GetAddressLine();
    ToggleDisplay('FriendPickerPanel');
}

function AddUid(uid)
{
    var targetElement = document.getElementById('UidsHidden');
    var toDiv = document.getElementById('ToDiv');
    
    targetElement.value += uid + ";";
    toDiv.innerHTML = GetAddressLine();
    ToggleDisplay('FriendPickerPanel');
}

function RemoveElement(elementId, targetId)
{
    var targetElement = document.getElementById(targetId);
    var toDiv = document.getElementById('ToDiv');
    
    var elements = ParseElements(targetElement.value);
    var newValue = "";
    var found = false;
    
    for (var i = 0; i < elements.length; i++) 
    {
        var current = elements[i];
        if(current.length > 0)
        {
            if(found) 
            {
                newValue += current + ";";
            }
            else 
            {
                if(current != elementId)
                {
                    newValue += current + ";";
                }
                else 
                {
                    found = true;
                }
            }
        }   
    }
    
    targetElement.value = newValue;
    toDiv.innerHTML = GetAddressLine();
}

function RenderToLine() 
{
    var toDiv = document.getElementById('ToDiv');
    if(toDiv != null) 
    {
        toDiv.innerHTML = GetAddressLine();
    }
}

function GetAddressLine()
{
    var emails = GetEmailAddressLine();
    var uids = GetUidsAddressLine();
    
    if((emails == "" || emails == null) && (uids == "" || uids == null)) 
    {
        return GetAddRecipientLink();
    }
    else 
    {
        return emails + " " + uids + " " + GetAddRecipientLink();
    }
}

function GetAddRecipientLink() 
{
    return "<a href=\"#\" onClick=\"ToggleDisplayAndFocus(\'FriendPickerPanel\', \'EmailInput\')\"><b>add recipient</b></a>";
}

function GetEmailAddressLine()
{
    var targetElement = document.getElementById('EmailsHidden');
    var ret = "";
    var addresses = ParseElements(targetElement.value);

    if(addresses != null)
    {
        for (var i = 0; i < addresses.length; i++) 
        {
            var address = addresses[i];
            if(address.length > 2) 
            {
                ret += address + "<span style=\"font-size:7pt;\"> [<a href=\"#\" onClick=\"RemoveElement(\'" + address + "\', \'EmailsHidden\')\">remove</a>]</span>; ";
            }
        }
    }

    return ret;
}

function GetUidsAddressLine()
{
    var targetElement = document.getElementById('UidsHidden');
    var ret = "";
    var uids = ParseElements(targetElement.value);

    if(uids != null)
    {
        for (var i = 0; i < uids.length; i++) 
        {
            var uid = uids[i];
            if(uid.length > 0) 
            {
                var screenName = document.getElementById("uid_" + uid).value;
                ret += screenName + "<span style=\"font-size:7pt;\"> [<a href=\"#\" onClick=\"RemoveElement(\'" + uid + "\', \'UidsHidden\')\">remove</a>]</span>; ";
            }
        }
    }
    
    return ret;
}

function ParseElements(line) 
{
    return line.split(';');
}

function GetChkBoxes()
{
    var retnode = [];
    var elements = document.getElementsByTagName('input');

    for(var i = 0; i < elements.length; i++)
    {
        if(elements[i].type == "checkbox") 
        {
            var id = elements[i].id;
            var l = id.length;
            
            if(id.substring(l - 9) == "msgchkbox") 
            {
                retnode.push(elements[i]);
            }
        }
    }
    
    return retnode;
}

function UpdateChkBoxes(allChkBox)
{
    var elements = GetChkBoxes();
    
    for(var i = 0; i < elements.length; i++)
    {
        elements[i].checked = allChkBox.checked;
    }
}

function AtLeastOneChecked()
{
    var elements = GetChkBoxes();
    var oneChecked = false;

    for(var i = 0; i < elements.length; i++)
    {
        if(elements[i].checked) 
        {
            oneChecked = true;
            break;
        }
    }
    
    return oneChecked;
}

function ConfirmDelete(el)
{
    if(AtLeastOneChecked())
    {
        if(confirm('Are you sure you want do delete these messages?')) 
        {
            SubmitForm(el);
        }
    }
    else 
    {
        alert('Please select the messages you want to delete');
    }
}

function IfCheckedSubmitForm(el)
{
    if(AtLeastOneChecked())
    {
        SubmitForm(el);
    }
    else 
    {
        alert('Please select the messages you want to delete');
    }
}


function GetListProperties(id, arrayOfListProperties)
{
    for (var i = 0; i < arrayOfListProperties.length; i++)
    {
        if (arrayOfListProperties[i].Id == id)
            return arrayOfListProperties[i];
    }
    
    return null;
}


function ToggleSelectCreateList(el, createNew)
{
    var form = FindParentForm(el);
    
    if(form)
    {
        var listSelectDiv = FindChildElementById(form, 'ListSelectDiv');
        var newListDiv = FindChildElementById(form, 'NewListDiv');
        var createNewList = form.CreateNewList;
    
        createNewList.value = createNew;
        if(createNew)
        {
            listSelectDiv.style.display = "none";
            newListDiv.style.display = "block";
        }
        else
        {
            newListDiv.style.display = "none";
            listSelectDiv.style.display = "block";
        }
    }
    
    return false;
}

function EnableListSelect(el)
{
    return ToggleSelectCreateList(el, false);
}

function EnableNewList(el)
{
    return ToggleSelectCreateList(el, true);
}

function SetListNameValidation(enable)
{
    window.Page_Validators[0].enabled = enable;
}

function UpdateWishProperties()
{
    var createNewList = WPJS.GetValue(document.getElementById('CreateNewList'));
    
    if(createNewList.toLowerCase() == "true")
    {
        var lt = WPJS.GetValue(document.getElementById('ListType'));
        var props = GetListProperties(lt, ListPicker_ListTypeProperties);
        
        // Retrieve the props.AccessType from UI selection
        props.AccessType = 0;
        for(var i = 0; i < 3; i++)
        {
            var atBtn = document.getElementById('La_' + i);
            if(WPJS.CheckBoxGetChecked(atBtn)) 
            {
                props.AccessType = atBtn.value;
                break;
            }
        }
        
        SetWishProperties(props, null);
    }
    else
    {
        var lid = WPJS.GetValue(document.getElementById('ListSelect'));
        var props = GetListProperties(lid, ListPicker_ListProperties);

        SetWishProperties(props, lid);
    }
    
    return false;
}


function SetWishProperties(props, listId)    
{    
    if(props == null) return;
    
    SetAvailable_WishAccessFormControl(props.AccessType);
        
	var priorityDiv = document.getElementById('PriorityPanel');
    if(props.SupportsPriority) 
        priorityDiv.style.display = "block";
    else  
        priorityDiv.style.display = "none";
    
    var recipientDiv = document.getElementById('RecipientPanel');
    if(props.SupportsRecipient) 
        recipientDiv.style.display = "block";
    else  
        recipientDiv.style.display = "none";
    
	var occasionDiv = document.getElementById('OccasionPanel');
    if(props.SupportsOccasion) 
        occasionDiv.style.display = "block";
    else  
        occasionDiv.style.display = "none";

	var notesDiv = document.getElementById('NotesPanel');
    if(props.SupportsNotes) 
        notesDiv.style.display = "block";
    else  
        notesDiv.style.display = "none";

	var reviewsDiv = document.getElementById('ReviewPanel');
    if(props.SupportsReviews) 
        reviewsDiv.style.display = "block";
    else  
        reviewsDiv.style.display = "none";

	var quantityDiv = document.getElementById('QuantityPanel');
    if(props.SupportsQuantity) 
        quantityDiv.style.display = "block";
    else  
        quantityDiv.style.display = "none";
        
    if (typeof(AlertProperties_NotifyListTypeChanged) != 'undefined')
		AlertProperties_NotifyListTypeChanged(props.EnableAlertsByDefault);
    
    if (typeof(ContributionProperties_SetPanelVisibility) != 'undefined')
		ContributionProperties_SetPanelVisibility(props.SupportsContributions);    
}

function AfterMoveCopy(operation, wid, api_response)
{
    CloseDialog('CopyMoveDiv_'+wid);
    $('button').removeClass('clicked');
    if(operation == "move" || operation == "delete")
    {
      $('#Wish_'+wid).slideUp(1000);
    }
    if(operation == "copy")
    {
       var d = WPJS.AlertWithTitle("Wish copied.", "Operation complete", 1000);
    }
}

function DoAjaxMoveCopy(form_obj)
{
  var op = WPJS.GetValue(form_obj["operation"]);
  var wid = WPJS.GetValue(form_obj["Wish.Id"]);
  var callback = function(data, textStatus){AfterMoveCopy(op, wid, data);};
  var url = "";
  
  if(op == "move"){ url = "/restapi/Wish/Edit/"+wid;}
  else if(op == "copy"){ url = "/restapi/Wish/Copy"; }

  jQuery.ajax({data: $(form_obj).serialize(), error: JqueryAjaxErrHandler, success: callback, type: "POST", dataType: 'xml', url: url});
}

function DoAjaxDelete(wid)
{
  var callback = function(data){AfterMoveCopy("delete", wid, data);}
  jQuery.ajax({data: '', error: JqueryAjaxErrHandler, success: callback, type: "POST", dataType: 'text', url: "/restapi/Wish/Delete/"+wid});
}


function FindChildElementById(parent, id)
{
    var children = parent.childNodes;
    
    if(children != null)
    {
        for (var i = 0; i < children.length; i++) 
        {
            if(children[i].id == id) 
            {
                return children[i];
            }
            
            var el = FindChildElementById(children[i], id);
            if(el != null)
            {
                return el;
            }
        }
    }

    return null;
}

////////////Summary view////////////////////////////////////////////

function showItem(id)
{
	if (showedItem == id)
		return;
    hideAllItems();
	showedItem = id;
	var pObj = document.getElementById(id).previousSibling;
	if (!isIE)
	{
	    pObj = pObj.previousSibling;
	}
	if (pObj.offsetLeft > 300)
	{
		document.getElementById(id).style.left = "380px";
	}
	else
	{
	    if (ShowFilter == "True")
	    {
    		document.getElementById(id).style.left = (parseInt(pObj.offsetLeft)+leftDif)+"px";
	    }
	    else
	    {
    		document.getElementById(id).style.left = (parseInt(pObj.offsetLeft)-2)+"px";
	    }
	}
	if (ShowFilter == "True")
	{
    	document.getElementById(id).style.top = (parseInt(pObj.offsetTop)+topDif+(isIE?15:0))+"px";
	}
	else
	{
    	document.getElementById(id).style.top = (parseInt(pObj.offsetTop)+topDif)+"px";
	}

	document.getElementById(id).style.left = (parseInt(document.getElementById(id).style.left) + leftIncrement) + "px";
	document.getElementById(id).style.top = (parseInt(document.getElementById(id).style.top) + topIncrement) + "px";
    document.getElementById(id).style.display = "inline";
}

function hideItem(id)
{
    hideAllItems();
}

function hideAllItems()
{
	showedItem = null;
    var divs = document.getElementsByTagName("DIV");
    for (var i=0; i<divs.length; i++)
    {
        if (divs[i].getAttribute("destination") && divs[i].getAttribute("destination") == "wish_description")
        {
            divs[i].style.display = "none";
        }
    }
}

function showMoreActions(p1)
{
    if (document.getElementById(p1).style.display == "none")
    {
        document.getElementById(p1).style.display = "inline"
    }
    else
    {
        document.getElementById(p1).style.display = "none"
    }
}

function EnsureEl(idOrEl)
{
	if(typeof(idOrEl) == "string")
		idOrEl = document.getElementById(idOrEl);
	return idOrEl;
}

function CopyValue(el1, el2)
{
	el1 = EnsureEl(el1);
	el2 = EnsureEl(el2);
	el2.value = el1.value;
}

function FlipCheckbox(el)
{
	el = EnsureEl(el);
	el.checked = !el.checked;
}

function UpdateDesign(idShow, idHide, uid) 
{
    SwitchDisplay(idShow, idHide);
    UpdateWidget(uid);
}

function UpdateWidget(uid)
{
    var skin = null;
    var txtColor = null;
    var widgetUrl = null;
    var width = null;
    var height = null;
    
    var listId = WPJS.GetValue(document.getElementById('ListSelect'));
    var domainUrl = WPJS.GetValue(document.getElementById('DomainUrl'));
    var userListUrl = WPJS.GetValue(document.getElementById('UserListUrl'));
    var rc = WPJS.GetValue(document.getElementById('ReferralCode'));
    var pkey = WPJS.GetValue(document.getElementById('PartnerKey'));
    var rssFeedUrl = encodeURIComponent(WPJS.GetValue(document.getElementById('RssFeedUrl')) + '?uid=' + uid + '&list=' + listId + '&rcgen=' + rc + '&pkey=' + pkey);
    if(document.getElementById('LargeDesign').style.display == "block") 
    {
        skin = WPJS.GetValue(document.getElementById('DesignSelectLarge'));
        if(skin == "Wishpot-Hotstuff.jpg")
        {
            txtColor = "0xffffff";
        }
        else
        {
            txtColor = "0x000000";
        }
        widgetUrl = WPJS.GetValue(document.getElementById('LargeWidgetUrl'));
        width = WPJS.GetValue(document.getElementById('LargeEmbedWidth'));
        height = WPJS.GetValue(document.getElementById('LargeEmbedHeight'));
    }
    else 
    {
        skin = WPJS.GetValue(document.getElementById('DesignSelectSmall'));
        txtColor = "0x000000";
        widgetUrl = WPJS.GetValue(document.getElementById('SmallWidgetUrl'));
        width = WPJS.GetValue(document.getElementById('SmallEmbedWidth'));
        height = WPJS.GetValue(document.getElementById('SmallEmbedHeight'));
    }

    var widgetDiv = document.getElementById('WidgetDiv');
    widgetDiv.style.width = width + "px";
    var widgetPreview = '<embed src="' + widgetUrl + '?feedUrl=' + rssFeedUrl + '&skin=' + skin + '&domain=' + domainUrl + '&txtColor=' + txtColor + ' allowScriptAccess="always"' + '" width="' + width + '" height="' + height + ' allowScriptAccess="always"' + '"></embed><br />';
    WPJS.SetInnerXHTML(widgetDiv, widgetPreview);
    
    var html = '<div style="width:' + width + 'px; padding:0px;">' + widgetPreview;
    html += '<div style="text-align:right; margin-top:15px; padding-right: 10px;"><a href="';
    html += userListUrl + '?uid=' + uid + '&list=' + listId + '&rc=' + rc + '&pkey=' + pkey + '" target="_blank" style="color:0x666666; font-family: Arial, Helvetica, sans-serif; font-size: 11px; text-decoration:none" title="View my Wish List"><b>View my wish list on Wishpot &raquo</b></a></div></div>';
    WPJS.SetValue(document.getElementById('HtmlSnippet'), html);
    
    var pconf={
	defaultContent: 'HtmlSnippet', 
	UIConfig: '<config><display showDesktop="false" showEmail="true" showBookmark="true" networksToHide="facebook" networksToShow="myspace, myspacecomment, friendster, orkut, bebo, tagged, blogger, hi5, livespaces, piczo, freewebs, livejournal, blackplanet, myyearbook, wordpress, vox, typepad, xanga, multiply, igoogle, netvibes, pageflakes, migente, *"></display><body><background background-color="#FFFFFF" corner-roundness="4"></background></body></config>'
	};
	Wildfire.initPost('190251', 'divWildfirePost', 400, 300, pconf);

}


function rgbToHex(rgbstring) {
	// RGB to HEX: "rgb(0, 70, 255)"
	if (rgbstring) {
		if (rgbstring.indexOf('rgb(') == -1) {
			return rgbstring;
		}
		var parts = rgbstring.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
		delete (parts[0]);
		for (var i = 1; i <= 3; ++i) {
		    parts[i] = parseInt(parts[i],0).toString(16);
		    if (parts[i].length == 1) parts[i] = '0' + parts[i];
		}
		var hexstring = parts.join('');
		return '#' + hexstring;	
	}
}

function normalizeStyleValues(string,optionalReferenceObj) {
	// RGB to HEX: "rgb(0, 70, 255)"
	if (string.indexOf('rgb') != -1) {
		var parts = string.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
		delete (parts[0]);
		for (var i = 1; i <= 3; ++i) {
		    parts[i] = parseInt(parts[i],0).toString(16);
		    if (parts[i].length == 1) parts[i] = '0' + parts[i];
		}
		var hexString = parts.join('');
		return '#' + hexString;
	}
	// Color values already in HEX
	else if (string.indexOf('#') != -1) {
		return string;
	}
	// Position strings and pixel values to percentages
	else if (string.indexOf('px') != -1 && optionalReferenceObj) {
		var objheight = jQuery(optionalReferenceObj).height();
		var objWidth = jQuery(optionalReferenceObj).width();
		var x = string.split(' ')[0];
		var y = string.split(' ')[1];
		x = x == '0px' ? '0%' : x == objWidth + 'px' ? '100%' : x == (objWidth/2) + 'px' ? '50%' : x;
		y = y == '0px' ? '0%' : y == objheight + 'px' ? '100%' : y == (objheight/2) + 'px' ? '50%' : y;
		string = x + ' ' + y;
		return string;
	}
	else {
		string = string.replace(/top/g,'0%');
		string = string.replace(/bottom/g,'100%');
		string = string.replace(/left/g,'0%');
		string = string.replace(/right/g,'100%');
		string = string.replace(/center/g,'50%');
		return string;
	}
}


