var product_id;

var IE6 = document.all && !window.opera && !window.XMLHttpRequest;

        function fnUpdateUrl_additional(){
		var url;
                var prod;
                var n;
                var h_ref = document.getElementById("addToBasket").href;
                var args = "?additional=";
                for(n=0;n<30;n++){
                        prod = document.getElementById('additional-'+n);
                        if(prod && prod.checked){
                                args = args + prod.value + "|"
                        }
                }
		url = h_ref + args;
                document.getElementById("addToBasket").href = url;
		return(url);
        }
        function fnUpdateUrl( product_id ){
            var url2;
            validUrl=true;
            if( document.getElementById("colour") ){
                var colour = document.getElementById("colour").value.replace(/-/,'.');
                if( colour == -1 ) validUrl=false;
                if( colour == 0 ) validUrl=false;
            } else {
                var colour = "X";
            }
            if( document.getElementById("productOptions") ){
                var option = document.getElementById("productOptions").value;
                if( option == -1 ) validUrl=false;
            }else{
                var option = "X";
            }
            if(!validUrl){
		alert("Please select from one of the available options");
		window.location = '#product_options';
		return;
            }

            var h_ref = document.getElementById("addToBasket").href;
            //var h_ref = $('#addToBasket').attribute('href');
            var url="/applogic/addtobasketinline/"+product_id;

            if(option == 'X' && colour == 'X'){
                document.getElementById("addToBasket").href=url;
                //$(".addToBasket").attribute('href',url);
            }else{
                url=url + "-" + colour + "-" + option;
                document.getElementById("addToBasket").href=url;
                //$(".addToBasket").attribute('href',url);
            }
		return(url)
        }

	var more_popup = null;
        function validateUrlNew(product_id, flag)
        {
            fnUpdateUrl(product_id);
            if(!validUrl){
		 return(false);
         	}
	    var url=fnUpdateUrl_additional();
            addToBasket(product_id, url, flag, 1);
		if (!IE6) {
			$("#box").load(
				"/default/ajax/popup_products.php",
				{
					product: product_id,
					bought: additional_bought.join('|')
				}
			);
			more_popup = $("#box").dialog({
				autoOpen: false,
				modal:true,
				resizable:false,
				width:'400',
				position:'top',
				title:'We also have these <b><u>related items</u></b> available...'
			});
			more_popup.dialog('open');
		}
		return(false);
        }
        function validateUrl(product_id, flag, quant)
        {
            fnUpdateUrl(product_id);
            if(!validUrl){
		 return(false);
         	}
	    var url=fnUpdateUrl_additional();
            addToBasket(product_id, url, flag, quant);
	    return(false);
        }

	function close_window()
	{
		//$("#box").dialog('close');
		more_popup.dialog('close');
	}

	function swap_out_image2 (photo_id) {
		for (var i = 1; i <= 4; i++) {
			var photo = document.getElementById('photo' + i);
			if (photo != undefined && photo != null) {
				document.getElementById('swap' + photo.value).style.display = 'none';
			}
		}
		document.getElementById('swap' + document.getElementById(photo_id).value).style.display = 'block';
	}

        function swap_out_image(argthis, target_id, iwidth, iheight, lightbox)
 {
                // argthis is passed the calling html item (an img)
                // iwidth is the incoming set width to scale the image to
                // iheight is the incoming set height to scale the image to
                // Function determines the restraining dimension and scales the image to the correct size
                // Function then switches out the target image for the source img via the src

                var target_image = document.getElementById(target_id);
                var source_image = argthis;

                //target_width = target_image.getAttribute("width");
                //target_height = target_image.getAttribute("height");

                target_width = iwidth;
                target_height = iheight;

                source_width = source_image.getAttribute("width");
                source_height = source_image.getAttribute("height");

                height_scale = target_height/source_height;
                width_scale = target_width/source_width;

                myscale = Math.min(height_scale, width_scale);

                final_height = source_height * myscale;
                final_width = source_width * myscale;

                target_image.setAttribute("src", source_image.getAttribute("src"));
                target_image.setAttribute("alt", source_image.getAttribute("alt"));
                target_image.setAttribute("width", final_width);
                target_image.setAttribute("height", final_height);

		if(lightbox != null && lightbox != undefined)
		{
			var links = new Array();
			var box = document.getElementById('right_Details');
			links = box.getElementsByTagName('a');
			var i = 0;
			var args = new Array();
			for(i=0;i<links.length;i++){
				var _rel = links[i].getAttribute('rel');
				if(_rel == 'lightbox[tt]')
				{
					args = links[i].getAttribute('href').split('&');
					args[2] = 'rec_id='+document.getElementById(lightbox).value;
					var link = args.join('&');
					links[i].setAttribute('href', link);
				}
			}
		}
        //alert ("tw" + target_width + "/n" +
        //"th" + target_height + "/n" +
        //"sw" + source_width + "/n" +
        //"sh" + source_height + "/n" +
        //"hs" + height_scale + "/n" +
        //"ws" + width_scale + "/n" +
        //"cs" + myscale + "/n" +
        //"fh" + final_height + "/n" +
        //"fw" + final_width);

 }
        function ReverseContentDisplay(d, flag) 
        {
                if(d.length < 1) { return; }
                if (navigator.userAgent && navigator.userAgent.indexOf("MSIE") >= 0)
                {
                        if(flag) { 
                                document.getElementById(d).style.height=90+'px';
                                document.getElementById('general_information').style.display='none'; 
                        } else { 
                                document.getElementById(d).style.height=40+'px'; 
                                document.getElementById('general_information').style.display='block';
                        }
                }else{
                        if(flag) { 
                                document.getElementById(d).style.setProperty( 'height', 90+'px', null); 
                            } else { 
                                    document.getElementById(d).style.setProperty( 'height', 40+'px', null); 
                            }
                }
        }

function newAddToBasket(product, url, _hide, flag)
{
	addToBasket(product, url, flag);
	var nextProduct = document.getElementById("next_product");
	$("#prod_" + _hide).hide("highlight", {}, "slow", function(){
		var prodBox = document.getElementById("products");
		var nextProd = document.createElement("div");
		nextProd.setAttribute("id", "prod_" + nextProduct.value);
		nextProd.setAttribute("class", "add_product");
		prodBox.appendChild(nextProd);
		$("#prod_"+ nextProduct.value).load(
			"/default/ajax/popup_products.php",
			{
				product: product_id,
				i: nextProd.value
			}
		);
		nextProduct.value++;
	});
}

var additional_bought = new Array();
function newerAddToBasket (product_id, additional_id, url) {
	addToBasket(additional_id, url);
	additional_bought[additional_bought.length] = additional_id;
	$("#box").load(
		"/default/ajax/popup_products.php",
		{
			product: product_id,
			bought: additional_bought.join('|')
		}
	);
}

function stop_suggesting()
{
	$("#box").load("/default/ajax/popup_products.php?stop-suggesting=true");
	close_window();
}
function showMore(current, next)
{
	var blockMore = document.getElementById('blockMore');
	if(blockMore == null || blockMore.value != 1){
		var prods = document.getElementById(current);
		var currentProds = prods.value.split("|");
		var amount = currentProds.length;
		var nextProd = document.getElementById(next);
		for(var i=0;i<amount;i++)
		{
			$("#prod_" + i).hide("highlight", {}, "slow");
		}
		var prodDiv = document.getElementById("products");
		$(prodDiv).load(
			"/default/ajax/popup_products.php",
			{
				product: product_id,
				min: nextProd.value
			}
		);
		var x, y, z;
		x = (nextProd.value) * 1;
		y = 2;
		z = x + y;
		prods.value = nextProd.value + '|' + (nextProd.value++);
		nextProd.value = z;
	}
}

/**
 * AJAX Login
 */

if (typeof jQuery != 'undefined') {
	$(document).ready(
		function () {
			$('#ajax_login_form').submit(ajaxLogin);
			$('input.ajax_cancel').click(
				function () {
					Boxy.get(this).hide();
				}
			);

			$('.review_ajax_login').click(function(){ ajaxShowLogin(); return false; });

			// Replace annoying Bazaar generated links
			//setTimeout(function () {
			//	ajaxOverwriteLinks('BVRRRatingSummaryLinkWriteID');
			//	ajaxOverwriteLinks('BVRRDisplayContentLinkWriteID');
			//	ajaxOverwriteLinks('BVRRRatingSummaryLinkWriteFirstID');
			//	ajaxOverwriteLinks('BVRRRatingSummaryNoReviewsWriteImageLinkID');
			//}, 2000);
		}
	);
}

function ajaxOverwriteLinks (container_id) {
	var container = document.getElementById(container_id);
	if (typeof(container) != 'undefined' && container != null) {
		var links = container.getElementsByTagName('a');
		if (links.length > 0) {
			links[0].onclick = function () {
				ajaxShowLogin();
				return false;
			};
		}
	}
}

function ajaxShowLogin() {
	if (typeof(ajax_login_userid) == 'undefined' || ajax_login_userid == null || ajax_login_userid == '') {
		ajaxPopup('ajax_login');
	} else {
		if (typeof(ajax_bought_product) == 'undefined' || !ajax_bought_product) {
			ajaxPopup('ajax_notbought');
		} else {
			ajaxShowForm();
		}
	}
}

function ajaxShowForm () {
	ajaxLoading('Thank you for waiting whilst we load the review submission form.');
	//window.location = 'http://reviews.betterbathrooms.com' + ajax_bazaar_test_mode + '/3586-en_gb/' + ajax_product_id + '/submission.htm?submissionurl=http://' + ajax_domain + '/applogic/bazaar_review&return=' + ajax_product_url;
	window.location = 'http://' + ajax_domain + '/applogic/review/' + ajax_product_id + '/';
}

function ajaxPopup (div_name,boxtitle) {
	if (div_name == undefined || div_name == null ||  div_name == '') {
		div_name = 'ajax_login';
	}
	if (boxtitle == undefined || boxtitle == null ||  boxtitle == '') {
		boxtitle = 'Submit Review';
	}
	ajaxError('');
	new Boxy(
		document.getElementById(div_name),
		{
			title: boxtitle,
			closeable: true,
			draggable: false,
			center: true,
			fixed: true,
			show: true,
			modal: true
		}
	);
}

function ajaxLoading (msg) {
	if (msg == null || msg == '') msg = 'Thank you for waiting whilst we attempt to log you in.';
	document.getElementById('ajax_loading_msg').innerHTML = msg;
	ajaxPopup('ajax_loading');
}

function ajaxLogin() {
	var username = document.getElementById('ajax_username');
	var password = document.getElementById('ajax_password');
	if (username != undefined && password != undefined && username.value != '' && password.value != '') {
		ajaxError('');
		Boxy.get($('#ajax_login')).hide();
		ajaxLoading();
		$.ajax({
			url: 'http://' + ajax_domain + '/applogic/logininline',
			type: 'POST',
			dataType: 'json',
			error: function() {
				Boxy.get($('#ajax_loading')).hide();
				ajaxPopup('ajax_login');
				ajaxError('Sorry, there was a problem trying to log you in, please try again.');
			 },
			success: ajaxLoginProcess,
			data: {
				email_address: username.value,
				password: password.value,
				login_type: 'ajax'
			}
		});
	} else {
		ajaxError('Please fill in your username and password.');
	}
	return false;
}

function ajaxLoginProcess (data) {
	Boxy.get($('#ajax_loading')).hide();
	if (data['error'] != undefined) {
		ajaxPopup('ajax_login');
		ajaxError(data['error']);
	} else {
		ajax_login_userid = data['userid'];
		if (typeof(ajax_bought_product) == 'undefined' || !ajax_bought_product) {
			ajaxPopup('ajax_notbought');
		} else {
			ajaxShowForm();
		}
	}
}

function ajaxError(msg) {
	var error = document.getElementById('ajax_error');
	if (error != undefined) error.innerHTML = msg;
}

if (typeof(addpro_popup) == 'function' || typeof(addpro_popup) == 'object') {
	$(document).ready(function(){ addpro_popup(); });
}

function ietest () {
	if (IE6) alert('IE6');
	else alert('Not IE6');
	alert(typeof(addpro_popup));
}

