function getObj(name)
{
	if( document.getElementById )
  	{
  		objHdl = document.getElementById( name );
  	}
  	else if( document.all )
  	{
		objHdl = document.all[ name ];
  	}
	else
	{
		window.alert("Sorry your browser is not compatable with this site");	
		return false;
	}

	return objHdl;
}

function linkToView()
{     
    // Get the link to name
    var linkName = arguments[ 0 ];
    
    // Build the link address
    var linkAddress = '/cgi-bin/viewPage.cgi?linkName=' + linkName;
    
    // Add each view data
    for ( var i = 1; i < arguments.length; i = i + 2 )
    {
        if ( arguments[ i ] == '__param__' )
        {
            arguments[ i + 1 ] = arguments[ i + 1 ].replace( "&", "%26" );
            linkAddress = linkAddress + '&' + arguments[ i + 1 ];
        }
        else
        {
            linkAddress = linkAddress + '&__view__' + arguments[ i ] + '=' + arguments[ i + 1 ];
        }
    } 
    
    location = linkAddress;
}

function forgotPassword()
{
 	// Function to retrieve members passwords
 	
 	// Get email value
 	objectInstance = document.getElementById( '__m__email' );          
	emailValue = objectInstance.value;
	
	if( emailValue == '' )
	{
		// if no email dont proceed
		alert("Please enter your email address");
	}
	else if( emailValue != '' )
	{
		// if email is valid send to script
		linkUrl = "/cgi-bin/memberScript/common/retrievePassword.cgi?__memberTypeName__=Member account&__m__email=";
		finalPath = linkUrl + emailValue;
		
		window.location = finalPath;
	}	
}

function parse_query_str( originalQueryString )
{
	// Parses url query string into an object
	
	queryObject = new Object();	
	
	valuePairs = originalQueryString.split( "&" );
	
	if( valuePairs[ 0 ].search( /\?/ ) == 0 )
	{		 
		newFirstValue = valuePairs[ 0 ].split( "?" );
		
		valuePairs.shift(); 
		
		valuePairs.unshift( newFirstValue[ 1 ] );		
	}
	
	for( i = 0; i < valuePairs.length; i++ )
	{
		pair = valuePairs[ i ].split( "=" );
		
		pairName = pair[ 0 ];
		
		queryObject[ pairName ] = pair[ 1 ];
	}
	
	return queryObject;
}

function submitSearch()
{
	// Function carrys out search
	var baseSql = "SELECT FROM `Standard product`";
	var catSql = "";
	var keySql = "";
	var catSearchValue = "";
	var currentVal = "";
	var keySearchValue = "";
	var catSearchUsed = 0;
	var newKeySearch = "";
	var catDesc = "";
	
	with( document.searchForm )
	{
		currentVal = catagorySelect.selectedIndex;
		catSearchValue = catagorySelect.options[ currentVal ].value;		
		
		keySearchValue = keywords.value;
	}	
	
	if( catSearchValue != "allCatagories" )
	{
		catSql = " WHERE `Standard product`.`section`.`__elementId__` = " + catSearchValue;	
		
		catSearchUsed = 1;
		
		// Build product description
		catDesc = "&__view__catagoryDesciptionView=SELECT FROM `Product section` WHERE `Product section`.`__elementId__` = " + catSearchValue;
		
	}
	
	if( keySearchValue != "" )
	{
		if( keySearchValue != "  Keywords..." )
		{
			matchReg = / /g;
			
			newKeySearch = keySearchValue.replace( matchReg, '%' );
			
			if( catSearchUsed == 1 )
			{
				keySql = escape(" AND `Standard product`.`description` LIKE '%" + newKeySearch + "%' OR `Standard product`.`title` LIKE '%" + newKeySearch + "%' AND `Standard product`.`publish` = 1");
			}
			else
			{
				keySql = escape(" WHERE `Standard product`.`description` LIKE '%" + newKeySearch + "%' OR `Standard product`.`title` LIKE '%" + newKeySearch + "%' AND `Standard product`.`publish` = 1");
			}	
		}
	}
	
	sqlQuery = baseSql + catSql + keySql;
	
	window.location = "/cgi-bin/viewPage.cgi?linkName=viewProducts&__view__productListingView=" + sqlQuery + catDesc;
	
}

// Cookie functions
    
function setCookie(name, value, expires, path, domain, secure)
{
	// Create/update a cookie.
	
	// Create the cookie string  
	var cookieString = 
	        name + "=" + escape( value ) +
	        ( expires ? "; expires=" + expires.toGMTString() : "" ) +
	        ( path ? "; path=" + path : "" ) +
	        ( domain ? "; domain=" + domain : "" ) +
	        ( secure ? "; secure" : "" );
	
	// Create/update the cookie
	document.cookie = cookieString;
}
    
    
function getCookie( name )
{
    // Get the value of a cookie using the specified name

    // Get a list of the cookies
    var cookieList = document.cookie;
    cookieList = cookieList + ';';
		
    // Use a regular expression to find the value of the name in the cookie 
    // list string.
	cookieMatch = cookieList.match( eval( '/' + name + '=(.*?);/' ) );

    // Check the cookie exists (a match was found)
    if ( cookieMatch )
    {
        // Return unescaped version of cookie
        return unescape( cookieMatch[ 1 ] );
    }

    // No cookie found, return null
    return;
}
    
    
function getCookieNameList()
{
	// Get a list of the cookies names
	
	// Get a list of the cookies
	cookieList = document.cookie;
	
	// Split the cookie list into name value pairs
	cookieNameValueList = cookieList.split( ";" );
	cookieNameList = Array();
	
	// Split each name=value pair and store the name
	for ( i = 0; i < cookieNameValueList.length; i++ )
	{
		// Split the name and value
		nameValue = cookieNameValueList[ i ].split( "=" );
		
		// Store the name
		cookieNameList.push( nameValue[ 0 ] );
	}
	
	return cookieNameList;
}

function addToBasket( elementId, productQuantityId, additionalProductInfo )
{	
	quantityObj = getObj( productQuantityId );
	quantity = quantityObj.value;
	
	if( quantity > 0 )
	{
		queryString = '&__item__' + elementId + ':quantity=' + quantity;
	
		if( additionalProductInfo )
		{
			// additionalProductInfo contains id to required value
			objHdl = getObj( additionalProductInfo );
			currentSelectedIndex = objHdl.selectedIndex;
			additionalProductInfoValue = objHdl.options[ currentSelectedIndex ].value;
			if( additionalProductInfoValue == '' )
			{
				window.alert("This product requires you to select an additional option. Please select one from the drop down menu.");	
				return;
			}
			else
			{	
				queryString = '&__item__' + elementId + ':quantity=' + quantity + '&__item__' + elementId + ':option=' + additionalProductInfoValue;		
			}
		}
		
		//window.alert("Send");
		window.location = "/cgi-bin/memberScript/common/addToBasket.cgi?__orderTypeName__=Member account order" + queryString;				
	}
    else
    {
    	window.alert("You must enter a valid quantity");
    }
}

function convertToPrice( price )
{
	// Format as a price
	price = price * 100.0;
	price = Math.round( price );
	price = price / 100.0;
	price = price.toFixed( 2 ); 

	return price
}

function addVat( priceWithoutVat, myVat )
{
 	priceWithVat = priceWithoutVat;

	if( myVat )
	{
		vatDecimal = myVat / 100.0;
	}
	else
	{
		vatDecimal = 0.175
	}

	vat = ( priceWithoutVat * vatDecimal );
	vat = vat * 100.0;
	vat = Math.round( vat );
	vat = vat / 100.0;     
	vat = vat.toFixed( 2 ); 

	priceWithVat = Number( priceWithVat ) + Number( vat );
	priceWithVat = priceWithVat * 100.0;
	priceWithVat = Math.round( priceWithVat );
	priceWithVat = priceWithVat / 100.0;     
	priceWithVat = priceWithVat.toFixed( 2 );

    finalValue = Number( priceWithVat )
    finalValue = finalValue.toFixed( 2 );

	vatData = new Object();
	vatData['priceWithVat'] = finalValue;
	vatData['vat'] = vat;

	return vatData;
}

function updateOrder( itemMap )
{
    updateString = '';
    
    for( i = 0; i < itemMap.length; i++ )
	{
    	// Loop through each record and
    	// create update string
    	currentObj = itemMap[ i ];
    	
    	updateString += '&__item__' + currentObj['elementId'] + ':quantity=' + currentObj['quantity'];
    }
    
    if( updateString != '' )
    {
    	window.location = '/cgi-bin/memberScript/common/updateBasket.cgi?__orderTypeName__=Member account order' + updateString;	
    }
	else
	{
		window.alert("An error has occured while attempting to updating your order");	
	}
}

function amendAddress( purpose, forwardLink )
{
	currentIndex = document.deliveryAddressForm.deliveryAddressSelect.selectedIndex;
	elementId = document.deliveryAddressForm.deliveryAddressSelect.options[ currentIndex ].value;
	
	switch( purpose )
	{
		case 'add':
				numberOfAddress = document.deliveryAddressForm.deliveryAddressSelect.options.length;
	
	    		if( numberOfAddress <= 5 )
	    		{
	    			if( forwardLink )
	    			{
	    				window.location = "/cgi-bin/viewPage.cgi?linkName=addAddress&__forwardName__=" + forwardLink;
	    			}
	    			else
	    			{
	    				window.location = "/cgi-bin/viewPage.cgi?linkName=addAddress";
	    			}
	    		}
	    		else
	    		{
	    			window.alert( 'You may only have 5 delivery addresses at one time. To add another you will have to remove or edit an existing one.' );
	    		}
	    		
	    		elementId = "add";
				break;
				
		case 'edit':
				baseUrl = '/cgi-bin/memberScript/common/updateMemberElement.cgi?__recordId__=';
				additionalUrl = '&linkName=editAddress&__userDefinedFormName__=pageForm&__maskingElementTypeId__=118&__memberElementName__=Delivery address';
				
				if( forwardLink )
    			{
    				linkUrl = baseUrl + elementId + additionalUrl + "&__forwardName__=" + forwardLink;
    			}
    			else
    			{
    				linkUrl = baseUrl + elementId + additionalUrl;
    			}
				break;
				
		case 'delete':
				baseUrl = '/cgi-bin/memberScript/common/deleteMemberElement.cgi?__recordId__=';
				additionalUrl = '&__memberElementName__=Delivery address';
				
				linkUrl = baseUrl + elementId + additionalUrl;
				break;
	}
	
	if( elementId != 0 )
	{
		window.location = linkUrl;
	}
	else
	{
		window.alert( 'Please select a delivery address first.' );
	}	
}

function getDeliveryMap()
{
	// Build delivery map
	deliveryMap = new Object();
	deliveryMapUk = new Object();
	deliveryMapNonUk = new Object();
	
	deliveryMapUk['80'] = 10.00;
	deliveryMapUk['80120'] = 7.50;
	deliveryMapUk['120250'] = 5.00;
	deliveryMapUk['250350'] = 0.00;
	deliveryMapUk['350'] = 0.00;
	
	deliveryMapNonUk['80'] = 20.00;
	deliveryMapNonUk['80120'] = 15.00;
	deliveryMapNonUk['120250'] = 12.50;
	deliveryMapNonUk['250350'] = 10.00;
	deliveryMapNonUk['350'] = 10.00;
	
	deliveryMap['uk'] = deliveryMapUk;
	deliveryMap['nonuk'] = deliveryMapNonUk;
		
	return deliveryMap;
}