
/******************************************
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;
}; 

function GoTo(url)
{
    window.location = url;
}

function FormatReturnUrl()
{
    var ruArg = 'ru=' + encodeURIComponent(window.location);
    return ruArg;
}

/******************************************
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 GoAddFriend(uid)
{
    GoTo("/my/friends/add.aspx?uid=" + uid);
}

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 GoImportList(alid,numPages)
{
    if(confirm('All the new items in this list will be imported. Are you sure you want to continue?'))
    {
		GoTo("/my/actions.aspx?action=alimport&alid=" + alid + "&np=" + numPages);
    }
}


/******************************************
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 GoDeleteList(lid)
{
    if(confirm('Are you sure you want to delete this list and all the items it contains?'))
    {
	    GoTo("/my/actions.aspx?action=delete&list=" + lid);
    }
}

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);
}


/*** Limit/count the number of characthers in a textarea ***/
function TaUpdate(el, cntId) 
{
     var ml = el.getAttribute("maxLength")*1;
     if (el.value.length>ml)
     {
     	el.value = el.value.substring(0,ml);
     }
     var left=ml-el.value.length;
     document.getElementById(cntId).innerHTML = left;
}

function TaPrevent(el) 
{
     //var ml = el.getAttribute("maxLength")*1;
     //return (el.value.length<ml);
     return true;
}

function CharsLeft(id) 
{
     var element = document.getElementById(id);
     var maxlength = element.getAttribute("maxLength")*1;
     var length = element.value.length*1;
     
     return maxlength - length;
}

/*** 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");
}

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 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 SubmitForm(el)
{
	while(el && (el.nodeName.toLowerCase() != "form"))
		el = el.parentNode;

	if(el)
		el.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;
}

function AppendInputTypeClasses() 
{  
	if (!document.getElementsByTagName )   
		return;  
	var inputs = document.getElementsByTagName('input');  
	var inputLen = inputs.length;  
	for(var i=0;i<inputLen;i++) 
	{   
		if(inputs[i].getAttribute('type'))    
			inputs[i].className += ' '+inputs[i].getAttribute('type');  
	} 
}

function WritePng(w,h,src,cn)
{
	var ieVer = IEVer();
	if(!ieVer || ieVer>6)
		return;

	var s = "<span style=\"display:inline-block;line-height:0px;font-size:1px;width:" + w + "px; height:" + h + "px;" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader";
	s = s + "(src=\'" + src + "\', sizingMethod='scale');\"";
	if(cn)
		s = s + " class=\"" + cn + "\"";
	s = s +	 "></span>";

	document.write(s);
}

/** 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 GetRadioButtons()
{
    var retnode = [];
    var elem = document.getElementsByTagName('input');
    for (var i = 0; i < elem.length; i++) 
    {
        if (elem[i].type == 'radio') retnode.push(elem[i]);
    }

    return retnode;
}

function GetListProperties(lid)
{
    var line = document.getElementById('ListProperties').value;
    var listProperties = line.split(';');

    if(listProperties != null)
    {
        for (var i = 0; i < listProperties.length; i++) 
        {
            var la = listProperties[i].split(':');
            if(la != null && la.length > 0 && la[0] == lid) 
            {
                return la;
            }
            
        }
    }
    
    return null;
}

function FindByValue(controls, v) 
{
    for (var i = 0; i < controls.length; i++) 
    {
        if(controls[i].value == v)
        {
            return controls[i];
        }
    }
}

function ChangeWishProperties(lselect)
{
    var lid = lselect.options[lselect.selectedIndex].value
    var props = GetListProperties(lid);
    if(props == null) return;

    var radioBtns = GetRadioButtons();
    var at = props[1];
    if(radioBtns != null)
    {
        var rb30 = FindByValue(radioBtns, "AccessType3");
        var rb20 = FindByValue(radioBtns, "AccessType2");
        var rb0 = FindByValue(radioBtns, "AccessType0");

        if(at == 30)
        {
            rb30.disabled = rb20.disabled = false;
        }
        else if(at == 20)
        {
            if(rb30.checked) 
            {
                rb30.checked = false;
                rb20.checked = true;
            }
            
            rb30.disabled = true;
            rb20.disabled = false;
        }
        else if(at == 0)
        {
            rb30.disabled = rb20.disabled = true;
            rb30.checked = rb20.checked = false;
            rb0.checked = true;
        }
    }
    
    var showPriority = props[2];
	var priorityDiv = document.getElementById('PriorityPanel');
    if(showPriority == "True") 
    {
        priorityDiv.style.display = "block";
    }
    else  
    {
        priorityDiv.style.display = "none";
    }
    
    var showRecipient = props[3];
	var recipientDiv = document.getElementById('RecipientPanel');
    if(showRecipient == "True") 
    {
        recipientDiv.style.display = "block";
    }
    else  
    {
        recipientDiv.style.display = "none";
    }
    
    var showOccasion = props[4];
	var occasionDiv = document.getElementById('OccasionPanel');
    if(showOccasion == "True") 
    {
        occasionDiv.style.display = "block";
    }
    else  
    {
        occasionDiv.style.display = "none";
    }

    var showNotes = props[5];
	var notesDiv = document.getElementById('NotesPanel');
    if(showNotes == "True") 
    {
        notesDiv.style.display = "block";
    }
    else  
    {
        notesDiv.style.display = "none";
    }

    var showReviews = props[6];
	var reviewsDiv = document.getElementById('ReviewPanel');
    if(showReviews == "True") 
    {
        reviewsDiv.style.display = "block";
    }
    else  
    {
        reviewsDiv.style.display = "none";
    }

    var showQuantity = props[7];
	var quantityDiv = document.getElementById('QuantityPanel');
    if(showQuantity == "True") 
    {
        quantityDiv.style.display = "block";
    }
    else  
    {
        quantityDiv.style.display = "none";
    }
}

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;
}

function GetStars(itemId)
{
    var retnode = [];
    for (var i = 1; i <= 5; i++) 
    {
        var elementId = "Star" + i + "_" + itemId;
        retnode.push(document.getElementById(elementId));
    }

    return retnode;
}

function DrawRating(rating, itemId) 
{
    var stars = GetStars(itemId);

    for(var i = 0; i < 5; i++)
    {
        if(i < rating)
        {
            stars[i].src = stars[i].src.replace("Star.gif", "Star_Selected.gif");
        }
        else
        {
            stars[i].src = stars[i].src.replace("Star_Selected.gif", "Star.gif");
        }
    }
    
    var ratingDiv = document.getElementById('RatingString_' + itemId);
    if(rating == 0) ratingDiv.innerHTML = "<b>No Rating</b>";
    else if(rating == 1) ratingDiv.innerHTML = "<b>I hate it!</b>";
    else if(rating == 2) ratingDiv.innerHTML = "<b>I don't like it</b>";
    else if(rating == 3) ratingDiv.innerHTML = "<b>I like it</b>";
    else if(rating == 4) ratingDiv.innerHTML = "<b>I really like it</b>";
    else if(rating == 5) ratingDiv.innerHTML = "<b>I love it!</b>";
}

function SetExistingRating(itemId)
{
    var rating = document.getElementById('RatingInput_' + itemId).value;
    DrawRating(rating, itemId);
}

function SetRating(rating, itemId)
{
    document.getElementById('RatingInput_' + itemId).value = rating;
}

////////////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;
}
