//change the price currency
function changeCurrency(dollar)
{
	var msg = "This will change the prices on the site to " + dollar +
	"\r\nAre you sure you want to continue?";
	if(window.confirm(msg))
	{
		document.frmLang.submit();
	}
	else
	{
		return false;
	}
}

function points_notify_ok_click()
{
	if($('#points_dont_notify_check:checked').val() == 'on') {
		document.getElementById('points_dont_notify_form').submit();
	}
}

function remove_order_points()
{
	$('#claimed_points').val("0");
	document.getElementById('change_points').submit();
}

function removeItem(itemId)
{
	$('#item_id').val(itemId);
	document.getElementById('formRemoveItem').submit();		
}
	//url redirect
  function redirect(url)
  {
    if(url != "0")
	{
	  window.location.href=url;

	}
  }
//verify when the customer intend to buy a item
function verify()
{
	if (f = document.forms['frmProduct'])
	{
		if (thisel = f.elements['color'])
		{
			if (thisel.value == "0") {
				//alert("Please choose a Colour for your garment.");
				$('#jqMsgText').html("Please choose a Colour for your garment.");
				$('#jqMsg').jqmShow();
				return false;
			}
		}
		if (thisel = f.elements['size'])
		{
			if (thisel.value == "0") {
				//alert("Please choose a Size for your garment.");
				$('#jqMsgText').html("Please choose a Size for your garment.");
				$('#jqMsg').jqmShow();
				return false;
			}
		}
		if (thisel = f.elements['qty'])
		{
			if (thisel.value == "0") {
				//alert("Please choose a quantity");
				$('#jqMsgText').html("Please choose a quantity.");
				$('#jqMsg').jqmShow();
				return false;
			}
		}
		return true;
	}
	else
	{
		return false;
	}

}
function hide(id)
{
	var elem = document.getElementById(id);
	elem.style.display = "none";
}
function show(id)
{
	var elem = document.getElementById(id);
	elem.style.display = "";
}

function chooseCountry(id, otherId)
{
	var elem = document.getElementById(id);
	if(elem.options[elem.selectedIndex].value == "Other")
	{
		show(otherId);
	}else
	{
		hide(otherId);
	}

}

function autotab(original,destination)
{
    if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
    destination.focus();

}
/**
@desc send Clan Member Confirmation email so they can activate there account
*/
function sendClanMemberConfirmEmail(scriptUrl, redirectTo)
{
	if(validateClanLogin())
	{
		var options = 
	    { 
	    	url:scriptUrl,
	    	type:'post',
	    	dataType:'json',
	        beforeSubmit:  function()
	        {
	        	show('processingAnim');
	        },
	        success: function(json)
	        {
				hide('processingAnim');
							
	        	if(typeof(json.error) == 'undefined')
	        	{
	        	    $('#messageDiv').addClass('error');
	        		$('#messageDiv').html('Unexpected errors, please refresh your browser and try again.');       		
	        	}
	        	else if(json.error != '')
	        	{
	        	   	$('#messageDiv').hide();
                    switch(json.error)
                    {
                        case 'success':
                        $('#incompleteProfile').hide();
	                    $('#messageFollowInstructions').show();	
                        break;
                        default:
                        $('#messageDiv').show().addClass('error').html(json.error);
                        //$('#dialogueCopy').hide();                        
                    }       		    		
	        	}
	        	else
	        	{
	        	    //window.location = redirectTo;
	        	    $('#jqMsgText').html("Unexpected error.");
					$('#jqMsg').jqmShow();
	        	}
	        	
	        },
	        error:function()
	        {
	            $('#messageDiv').html('Unexpected errors, please refresh your browser and try again.');         		        				
	            hide('processingAnim');
	        }
	
	    };	    
	    // bind form using 'ajaxForm' 
    	$('#frmClanSwaziLogin').ajaxSubmit(options);	
	}
	
	return false;
}

/**
@desc Authenticate Clan Member login
*/
function authenticateClanMember(scriptUrl, redirectTo)
{
	if(validateClanLogin())
	{
		var options = 
	    { 
	    	url:scriptUrl,
	    	type:'post',
	    	dataType:'json',
	        beforeSubmit:  function()
	        {
	        	show('processingAnim');
	        },
	        success: function(json)
	        {
				hide('processingAnim');
				//Set all try again links to hide eror messages and show login form
				$('a.tryAgain').click(function()
				{
				    $('div.errorMessage').hide();
				    $('#dialogueCopy').show();
				});
				
	        	if(typeof(json.error) == 'undefined')
	        	{
	        	    $('#messageDiv').addClass('error');
	        		$('#messageDiv').html('Unexpected errors, please refresh your browser and try again.');       		
	        	}
	        	else if(json.error != '')
	        	{
	        	    $('#messageDiv').hide();

				    switch(json.error)
				    {
				        case 'incorrect-password':
				        $('#messageIncorrectPassword').show();
	        		    $('#dialogueCopy').hide();
				        break;
				        case 'not-registered':
				        $('#notRegistered').show();
	        		    $('#dialogueCopy').hide();
				        break;
				        case 'incomplete-profile':
				        $('#incompleteProfile').show();
	        		    $('#dialogueCopy').hide();
				        break;
				        default:
				        $('#messageDiv').show().addClass('error').html(json.error);
	        		    //$('#dialogueCopy').hide();
				            
				    }
	        		    		
	        	}
	        	else
	        	{
	        		//alert(redirectTo);
	        	    window.location = redirectTo;
	        	}
	        	
	        },
	        error:function()
	        {
	            $('#messageDiv').html('Unexpected errors, please refresh your browser and try again.');         		        				
	            hide('processingAnim');
	        }
	
	    };
	    
	    // bind form using 'ajaxForm' 
    	$('#frmClanSwaziLogin').ajaxSubmit(options);	
	}
	
	return false;
}

function forgotPasswordLink(scriptUrl, redirectTo)
{
	var email = $('#username').val();
	$('#email').val(email);
	
	clanMemberForgot(scriptUrl, redirectTo);
	
	hide("forgotFormTable");
	
	$('#clanSwaziLogin').jqmHide();
	$('#clanSwaziForgot').jqmShow();
}

function clanMemberForgot(scriptUrl, redirectTo)
{
	if($('#email').val() == '')
    {
        $('#jqMsgText').html("Please enter an email address.");
		$('#jqMsg').jqmShow();
    }
	else
	{
		var options = 
	    { 
	    	url:scriptUrl,
	    	type:'post',
	    	dataType:'json',
	        beforeSubmit:  function()
	        {
	        	
	        },
	        success: function(json)
	        {
				hide('forgotProcessingAnim');
	        	if(typeof(json.error) == 'undefined')
	        	{
	        		show("forgotFormTable");
	        	    $('#forgotMessageDiv').addClass('error');
	        		$('#forgotMessageDiv').html('Unexpected errors, please refresh your browser and try again.');       		
	        	}
	        	else if(json.error != '')
	        	{
	        		show("forgotFormTable");
	        		$('#forgotMessageDiv').addClass('error');
	        		$('#forgotMessageDiv').html(json.error);    		
	        	}
	        	else
	        	{
	        	    //window.location = redirectTo;
	        	    $('#forgotMessageDiv').html('Please check your email for your new password.'); 
	        	}
	        	
	        },
	        error:function()
	        {
	        	show("forgotFormTable");
	        	hide('forgotProcessingAnim');
	            $('#forgotMessageDiv').html('Unexpected errors, please refresh your browser and try again.');         		        	
	        }
	
	    };
	    hide("forgotFormTable");
	    show('forgotProcessingAnim');
	    // bind form using 'ajaxForm' 
    	$('#frmClanSwaziForgot').ajaxSubmit(options);	
	}
	return false;
}

function addToMailingList(scriptUrl, redirectTo)
{    
    var options = 
    { 
    	url:scriptUrl,
    	type:'post',
    	dataType:'json',
        beforeSubmit:  function()
        {
        	$('#dialog').jqmShow(); 
        	$('#message').hide();
        	$('#processing').show();      	
        },
        success: function(json)
        {
             $('#message').show();
             $('#processing').hide();
        	if(typeof(json.error) == 'undefined')
        	{

        	    $('#message').addClass('error');
        		$('#message').html('Unexpected errors, please refresh your browser and try again.');       		
        	}
        	else if(json.error != '')
        	{
        		
        		$('#message').addClass('error');
        		$('#message').html(json.error);    		
        	}
        	else
        	{
        	    $('#message').removeClass('error');
        	    $('#message').html('You have been successfully added');
        	}
        	
        },
        error:function()
        {
            $('#processing').hide();
            $('#message').addClass('error').show().html('Unexpected errors, please refresh your browser and try again.');         		        	
        }

    }; 

    // bind form using 'ajaxForm' 
    $('#frmEmailSignUp').ajaxSubmit(options);		
	return false;
}

/**
@desc Menu for tabs
*/
jQuery.menu = {
    dropDownFadeDuration: 180,
    mainImages: ['farming_and_agriculture.jpg','hunting.jpg', 'outdoors_and_leisure.jpg', 'clan_swazi.jpg'],
    init: function()
    {
        //Hide all content tabs
        jQuery.menu.hideContentTabs();
        
        //Set Handlers
        $('#n-farming a').click(function()
        {
            jQuery.menu.showContentTab($(this).attr('href'));
            return false;
        });
        $('#n-hunting a').click(function()
        {
            jQuery.menu.showContentTab($(this).attr('href'));
            return false;
        });
        $('#n-outdoor a').click(function()
        {
            jQuery.menu.showContentTab($(this).attr('href'));
            return false;
        });
        $('#n-swazi-clan a').click(function()
        {
            jQuery.menu.showContentTab($(this).attr('href'));
            return false;
        });
        
        //Drop down close button
        $('#navlist a.closeDropdown').click(function()
        {
            $(this).parent().hide();
            $(this).parent().parent().removeClass('active');
            return false; 
        });
        
        //Footer Links
        $('#fnav-farming').click(function()
        {
            jQuery.menu.showContentTab('#farming_and_agriculture');
            return false;
        });
        $('#fnav-hunting').click(function()
        {
            jQuery.menu.showContentTab('#hunting');
            return false;
        });
        $('#fnav-outdoor').click(function()
        {
            jQuery.menu.showContentTab('#outdoor_and_leisure');
            return false;
        });
        $('a.joinClanSwazi, #clanIconLink').click(function()
        {
            jQuery.menu.showContentTab('#swazi_clan');
            return false;
        });
        
        $('#navlist li a.parent').each(function()
        {
            $(this).click(function()
            {
                var parent = $(this).parent();
                jQuery.menu.removeDropDownClassNames();
                jQuery.menu.hideDropDowns();
                if($(parent).attr('id') == 'n-swazi-clan-internal' && $(parent).hasClass('loggedout'))
                {
                    //Do nothing               
                }
                else
                {
                    $(this).parent().addClass(($(this).hasClass('active'))?'':'active');
                    $(this).hide();
                    $(this).fadeIn(jQuery.menu.dropDownFadeDuration);
                    $(this).next('div.dropdown').fadeIn(jQuery.menu.dropDownFadeDuration);
                    return false;
                }                              
                
            });
        });        
    },
    addImage: function(id, idx)
    { 
        if($(id + ' img').hasClass('mainImage'))
        {
            $('img.mainImage').remove();
        }
        var newImage = new Image();
        newImage.onload = function()
        {
            $(id).prepend('<img src="/images/home/' + jQuery.menu.mainImages[idx] + '" width="970" height="426" class="mainImage">'); 
            $(id + ' div.tabContentWrapper').fadeIn('medium');               
        }
        newImage.src = '/images/home/' + jQuery.menu.mainImages[idx];                
    },
    showContentTab: function(id)
    {
        jQuery.menu.hideContentTabs();
        jQuery.menu.removeDropDownClassNames();        
        
        if(id == '#swazi_clan')
        {
            $('#btm-nav').hide();
        }
        else
        {
            $('#btm-nav').show();
        }
        switch(id)
        {            
            case '#farming_and_agriculture':
                $('#homeImage').hide();
                jQuery.menu.addImage(id, 0);                
            break
            case '#hunting':
                $('#homeImage').hide();
                jQuery.menu.addImage(id, 1);
            break;
            case '#outdoor_and_leisure':
                  $('#homeImage').hide();
                  jQuery.menu.addImage(id, 2);
            break;
            case '#swazi_clan':
                $('#homeImage').hide();                
                jQuery.menu.addImage(id, 3);
            break;            
            default: $('#homeImage').show();
        }
        $(id).fadeIn('medium');
    },
    hideContentTabs: function()
    {
        $('div.tabContent').each(function()
        {
            $(this).hide();
        });
    },
    hideDropDowns: function()
    {
        $('div.dropdown').hide();
    },
    removeDropDownClassNames: function()
    {
        $('#navlist li').each(function()
        {
            if($(this).hasClass('active'))
            {
                $(this).removeClass('active');
                jQuery.menu.hideDropDowns();
            }
        });
    }
};

function chooseDeliveryCountry(url, isChosen)
{
	if(isChosen)
	{
		document.location.href = url;
	}else
	{
		$('#jqm_url').val(url);
		$('#dialogCountry').jqmShow();
	}
	
}

function viewFreightRegions()
{
	$('#jqm_url').val('');
	$('#dialogCountry').jqmShow();	
}

function doChooseDeliveryCountry(elem)
{
	if(elem.selectedIndex == (elem.options.length - 1))
	{
		$('#otherDeliveryCountryContainer').show();
	}
	else
	{
		$('#otherDeliveryCountryContainer').hide();
		$('#otherDeliveryCountry').val('');
	}
	
}

function validateFreightRegion(id)
{
	if(document.getElementById(id).selectedIndex <= 0)
	{
		$('#jqMsgText').html("Please choose a region.");
		$('#jqMsg').jqmShow();
		return false;
	}else
	{
		return true;
	}
	
}

function buildAddress(dealer, address)
{
    var addressArray = address.split(',');
    var formattedAddress = '';
    formattedAddress += '<b>' + dealer + '</b><br>';
    for(var i=0; i<(addressArray.length-1); i++)
    {
        formattedAddress += addressArray[i] + '<br>';
    }
    return formattedAddress

}

function initialize(dealer, address)
{
	if (GBrowserIsCompatible())
	{
		var map = new GMap2(document.getElementById("map_overlay"));
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(address,
    		function(point) 
    		{
    			if (!point) 
    			{
    				alert(address + " not found");
    			}
    			else 
    			{
    				map.setCenter(point, 15);
    				var marker = new GMarker(point, {draggable: false});
    				map.addOverlay(marker);
    				map.addControl(new GLargeMapControl());
    				//map.addControl(new GLargeMapControl3D());
    				map.addControl(new GMapTypeControl());
    				map.addControl(new GOverviewMapControl());
    				GEvent.addListener(marker, "dragend", function() 
    				{
    					var s = "" + marker.getPoint(marker);
    					s = s.replace('/\(/g', "");
    					s = s.replace('/\)/g', "");
    					s = s.split(", ");
    				});

    				marker.openInfoWindowHtml(buildAddress(dealer, address));
    			}
    		}
    	);
	}
}

//if (window.attachEvent) window.attachEvent("onload", sfHover);
function capLock(e)
{
    kc = e.keyCode?e.keyCode:e.which;
    sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
    if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
    {
        document.getElementById('capsOn').style.visibility = 'visible';
    }
    else
    {
        document.getElementById('capsOn').style.visibility = 'hidden';
    }
}

function validateClanLogin()
{
    var msg = '';
    if($('#username').val() == '')
    {
        msg +='Please enter your username (Email Address)' + "\n";
    }
    
    if(msg)
    {
        $('#jqMsgText').html(msg);
		$('#jqMsg').jqmShow();
        return false;
    }
    else
    {
        return true;
    }
}

function tr_change_password(elem)
{
	document.getElementById('tr_change_password1').style.display = (elem.checked?'':'none');
	document.getElementById('tr_change_password2').style.display = (elem.checked?'':'none');

}

function change_currency(curr)
{
	$('#curr').val(curr);
	$("#cur_displ").text(curr);
	
	if(curr == "NZD")
	{
		$('#remember_pref').attr('checked', true);
		$('#switch_currency').submit();
	}
	else
	{
		$('#currencyDialog').jqmShow();
		$('#curr_drop').hide();
	}
	
	return false;
}

function currency_close()
{
    var $this = $('#curr_drop').get(0);
    if($this.style.display == 'block')
    {
        $this.style.display = 'none';
    }
    
    return false; 
}

function gst_toggle()
{
	$('#GSTDialog').jqmShow();
	//$('#gstToggle').submit();
}