//Setup Toolbar link Events
function setToolbar(thisPageTitle, thisPageUrl)
{
    var sendToFriendMessage = $('#SendToFriendMessage');
    $('#bookmarkHomepage a').click(function()
    {
        //setHomePage();
        if($.browser.msie)
    	{
    		 this.style.behavior='url(#default#homepage)';
    	  	 this.setHomePage(window.location.href);
    	}
    	else if($.browser.mozilla)
    	{
    	    alert('If you are using Firefox please use Ctl+D to bookmark this page');
    	}
        return false;
    });
    $('#bookmarkThisPage a').click(function()
    {
        createBookmarkLink(thisPageTitle, thisPageUrl); return false;
    });
    $('#printThisPage').click(function()
    {
        window.print(); return false;
    });
    //SEND TO A FRIEND FORM
    $('#sendToFriend a').click(function()
    {
        $('#sendToAFriendBody').fadeIn('normal'); return false;
    });
    $('#sendToFriendClose a').click(function()
    {
    	$('#sendToAFriendBody').fadeOut('normal');
    	sendToFriendMessage.css('display', 'none');
    	return false;
    });
	sendToFriendMessage.css('display', 'none');
}

function setPhotoThumbs()
{
    var thumbs = $('.thumbs img');
    thumbs.css('opacity', 0.5);
    thumbs.hover(function(){$(this).css('opacity', 1)}, function(){$(this).css('opacity', 0.5)});
}

// BOOKMARK FUNCTIONS
function createBookmarkLink(title, url)
{
    url = (url !='')? url : 'http://www.mooloo.co.nz';
    if($.browser.msie)
    {
        // IE Favorite
		window.external.AddFavorite( url, title);
    }
    else if($.browser.mozilla)
    {
        alert('If you are using Firefox please use Ctl+D to bookmark this page');
    }
    return false;
}

function emailCheck(emailStr)
{
    // checks if the e-mail address is valid
	var email=/^[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_\.-][A-Za-z0-9]+)*\.([A-Za-z]){2,4}$/i;
	return(email.test(emailStr));
}

function doSendToFriend(url)
{
	var friendEmail = $('#friend_email').val();
	var SendToFriendMessage = $('#SendToFriendMessage');

    if(!emailCheck(friendEmail))
    {
    	alert('Please enter your friends Email address.');
    	return false;
    }
    var yourEmail = $('#your_email').val();
    if(!emailCheck(yourEmail))
    {
    	alert('Please enter your Email address.');
    	return false;
    }
    var contentUrl = window.location.href;

    $("#processing").ajaxStart(function(){
       SendToFriendMessage.hide();
       SendToFriendMessage.empty();
       $(this).show();
    });
    $('#friend_email').ajaxSuccess(function(){
        $(this).val('');
    });
    $('#your_email').ajaxSuccess(function(){
        $(this).val('');
    });
    $("#processing").ajaxComplete(function(){
       $(this).hide();
       SendToFriendMessage.css('display','block');
    });
    $("#SendToFriendMessage").load(url, {your_email: yourEmail, friend_email: friendEmail, content_url: contentUrl});

}

function popupVideo(url)
{
	window.open('/video_popup.php?url='+url, '', 'width=458, height=480');
}

function reloadAuctionInfo(url, auctionoid, expiredUrl)
{

	var refresh = document.getElementById('refresh');
	var sec = parseInt(refresh.options[refresh.selectedIndex].value);
	if(!isNaN(sec) && sec>0)
	{
		$.get(url,
			function (xml)
			{
				var items = $('item', xml);
				var itemStatus = 0;
				var itemCurrentBid = 0;
				var itemTotalBids = 0;
				var itemPublished = 0;
				var val = 0;
				var minimunBid = 0;
				items.each
				(	function()
					{
						val = parseInt(this.getAttribute('value'));
						switch(this.getAttribute('id'))
						{
							case "current_bid":
								itemCurrentBid = val;
								break;
							case "total_bids":
								itemTotalBids = val;
								break;
							case "status":
								itemStatus = val;
								break;
							case "published":
								itemPublished = val;
								break;
						}
					}
				)
				//query would be not executed successfully
				if(itemStatus !=0 && !isNaN(itemStatus))
				{
					minimunBid = (itemTotalBids>0?(itemCurrentBid+1):itemCurrentBid);
					if(!isNaN(itemCurrentBid) && itemCurrentBid > 0 && itemTotalBids>0)
					{
						$('#current_bid').html("<b>Current Bid:</b> $"+ itemCurrentBid);
					}
					else
					{
						$('#current_bid').html('<b>Current Bid:</b> $--');
					}

					$('#total_bids').html('<b>Total Bids:</b> ' + itemTotalBids);
					$('#lastest_bid').val((itemCurrentBid) + '');
					if(itemPublished == 0)
					{
						window.location.href=expiredUrl;
					}
				}
			}
		)
		setTimeout("reloadAuctionInfo('" + url + "', " + auctionoid + ", '" + expiredUrl +"')", sec * 1000);
	}
}

function doSumbitRequestType(type)
{
	var elem = document.getElementById('auction_request_type');
	if(elem)
	{
		elem.value = type;
		document.frmLoginRequest.submit();
	}
}

function doPlaceBid()
{
	var NewBid = parseInt($('#new_bid').val());
	var minimumBid = parseInt($('#minimum_bid').val());
	if(!isNaN(NewBid)&& NewBid > 0 && NewBid >= minimumBid)
	{
		document.frmPlaceBid.submit();
	}else
	{
		alert('Oops! You need to bid at least $' + (minimumBid));
	}
}

function removeItem(itemId)
{
	document.formRemoveItem.item_id.value = itemId;
	document.formRemoveItem.submit();
}

function purchase(allowNaming)
{
	if(allowNaming )
	{
		var elem = document.getElementById('namingNumbering');
		if(elem.style.display== 'none' && window.confirm('Do you want to have personal name and/ or number on the back of jersey'))
		{
			elem.style.display = '';
			return false;

		}else
		{

		}
	}
	document.formPurchase.submit();
}

function checkPurchase()
{
	var size = document.formPurchase.size;
	var colour = document.formPurchase.colour;
	var qty = document.formPurchase.qty;
	var msg = "";

	if(typeof size != 'undefined')
	{
		if(size.tagName.toUpperCase() == 'SELECT')
		{
			if(size.options[size.selectedIndex].value=="" || size.options[size.selectedIndex].value=="0")
			{
				msg += 'Please choose a size.\n\r';
			}
		}

	}
	if(typeof colour != 'undefined')
	{
		if(colour.tagName.toUpperCase() == 'SELECT')
		{
			if(colour.options[colour.selectedIndex].value==""  || colour.options[colour.selectedIndex].value=="0")
			{
				msg += 'Please choose a colour.\n\r';
			}
		}

	}
	if(typeof qty != 'undefined')
	{
		if(qty.tagName.toUpperCase() == 'SELECT')
		{
			if(qty.options[qty.selectedIndex].value=="" || qty.options[qty.selectedIndex].value=="0")
			{
				msg += 'Please choose a quantity.\n\r';
			}
		}

	}
	if(msg != '')
	{
		alert(msg);
		return false;
	}
	else
	{
		return true;
	}
}
function doPersonalPurchase()
{
	var name = document.getElementById('nameField');
	var number = document.getElementById('numberField');
	var msg = "";
	if(name.value.length > 13)
	{
		msg += 'You are only allowed to have a name which is not longer than 13 characters on back of jersey \n\r ';
	}
	var re = /[0-9]+/;
	if(number.value != '' )
	{
		if(!re.test(number.value))
		{
			msg += "You are allowed to have a number which contain digits only on the back of jersey.\n\r";
		}
	}

	if(msg != '')
	{
		alert(msg);
		return false;
	}
	else
	{
		document.formPurchase.submit();
		return true;
	}

}

function setNamingNumbering(itemId)
{
		var elem = document.getElementById('linkPurchase' + itemId);
		var t = elem.title || elem.name || null;
		var g = elem.rel || false;
		TB_show(t,elem.href,g, "<a href='#' id='TB_closeWindowButton'>Go Back</a>&nbsp;<a href='#' onclick='return ChangePersonalPurchase(" + itemId + ");'>Change</a>");
		elem.blur();
		return false;
}

function ChangePersonalPurchase(itemId)
{
	var name = document.formViewOrder.elements['item[' + itemId +  '][name]'];
	var number = document.formViewOrder.elements['item[' + itemId +  '][number]'];
	var newName = document.TB_FORM.elements['item[' + itemId +  '][name]'];
	var newNumber = document.TB_FORM.elements['item[' + itemId +  '][number]'];
	var msg = "";
	if(newName.value.length > 13)
	{
		msg += 'You are only allowed to have a name which is not longer than 13 characters on back of jersey \n\r ';
	}
	var re = /[0-9]+/;
	if(newNumber.value != '' )
	{
		if(!re.test(newNumber.value))
		{
			msg += "You are allowed to have a number which contain digits only on the back of jersey.\n\r";
		}
	}
	if(msg != '')
	{
		alert(msg);

		return false;
	}else
	{
		name.value = newName.value;
		number.value = newNumber.value;
		document.formViewOrder.submit();
		return true;
	}
}

function setPurchaseType()
{
    var s = $('#purchaseType');
    var link = $('#linkPurchase')
    link.css('display', 'none');
    s.change(function(){
        if(this.options[this.selectedIndex].value == 'personalised')
        {
            link.css('display', 'inline');
            $('#linkPurchaseBlank').css('display', 'none');
        }
        else
        {
            link.css('display', 'none');
            $('#linkPurchaseBlank').css('display', 'inline');
        }
    });
}
function showImageOverlay()
{
    var imageOverlayBox = $('#namingNumbering');

    $('#linkPurchase').click(function()
    {
        imageOverlayBox.fadeIn('slow');
    });
    $('#closeWindowButton').click(function()
    {
        imageOverlayBox.fadeOut('slow');
    });
    $('#purchaseLink').click(function()
    {
        return doPersonalPurchase();
    }
    );
}


function setImageOverlay()
{
    var nameInput = $('#nameField');
    var numberInput = $('#numberField');

    var nameTarget = $('#nameOverlay');
    var numberTarget = $('#numberOverlay');

    nameInput.keyup(function()
    {
        nameTarget.html(this.value);
    });

    numberInput.keyup(function()
    {
        numberTarget.html(this.value);
    });

}

function changeDelivery(elemId)
{
	var deliveryElem = document.getElementById(elemId);
	var deliveryCharge = deliveryElem.value;
	var subTotal = document.getElementById('sub_total');
	var floatDeliveryCharge = parseFloat(deliveryCharge);
	$('#delivery_charge').html('$' + floatDeliveryCharge.toFixed(2)) ;
	$('#total').html('$' + (parseFloat(subTotal.value) + floatDeliveryCharge).toFixed(2));

}

function stripeTables(id)
{
    $(id +' tr').each(function(i)
    {
        if(i %2){
            $(this).addClass('even');
        }
    });
}


function submitPoll(oid)
{
    var frm = document.getElementById('frmPolls')
    var el = document.getElementById('pollAnswer');
    if(oid)
    {
        el.value = oid;
        frm.submit();
    }
    return false;
}

