// Function to request popup html
var $popup = {
	length: 0
};

// Function to request popup html
function toggle_popup(page) {
	if ($('#timed-popup')) {
		$('#timed-popup').remove();
	}

  showOverlay();

	switch(true) {
		case ($('#order_direct_popup').length > 0):
			$popup = $('#order_direct_popup');
			break;

		case ($('#order_direct_popup_phone').length > 0):
			$popup = $('#order_direct_popup_phone');
			break;

		case ($('#color-popup').length > 0):
			$popup = $('#color-popup');
			break;

    case ($('#sizes-popup').length > 0):
			$popup = $('#sizes-popup');
			break;

		default:
			$popup = {
				length: 0
			};
	}

	if ($popup.length > 0) {
		correct_view();
		if ($popup.css("display") == "block") {
			//fix_ie6_select();
			$popup.remove();
		} else {
			//fix_ie6_select();
			$popup.show();
		}
	} else {
		var request = "page="+page;
		if (typeof($current_url) != "undefined") {
			request += "&url="+$current_url;
		}
		if (typeof($prod) != "undefined") {
			request += "&prod="+$prod;
		}
    if (typeof($buy_online) != "undefined") {
      request += "&buyOnlineID="+$product_id;
    }
		var rel = "";
		if (window.location.toString().indexOf("/careers") != -1) {
			rel = "../";
			request += "&from_careers=true";
		} else {
			rel = "./";
		}

		// set phone number according to Brilliant tracking
		request += "&order_direct_telephone="+$("#order-direct-contact-telephone").html();

		$.post(rel + "how-to-buy/order-direct-popup/", request, function(response) {

		if (response.msg != "OK") {
			return false;
		}

		// all good, lets render the popup
		if ($popup.length == 0) {
			$("#container").append(response.html);

			switch(true) {
				case ($('#order_direct_popup').length > 0):
					$popup = $('#order_direct_popup');
					break;

				case ($('#order_direct_popup_phone').length > 0):
					$popup = $('#order_direct_popup_phone');
					break;

				case ($('#color-popup').length > 0):
					$popup = $('#color-popup');
					break;

        case ($('#sizes-popup').length > 0):
					$popup = $('#sizes-popup');
					break;

        case ($('#need-help-popup').length > 0):
					$popup = $('#need-help-popup');
					break;

				default:
					$popup = {
						length: 0
					};
			}
		}

    // sort out heights
    $("#option-call-us").height($("#option-call-you").height());

				setTimeout(function(){
					correct_view();
				},0.1);

        if (typeof($buy_online) != "undefined" && $buy_online === true) {
         _gaq.push(['_trackPageView', '/goal/order_direct_form_view/order-online/'+page]);
        }
				// add in pageTracker event
				_gaq.push(['_trackPageview',"/goal/order_direct_form_view/"+page]);

				// Wired Minds for when the form was loaded
				//Pricegrabber
				elementImg = "<img src='https://www.pricegrabber.com/conversion.php?retid=13003' height='1' width='1' />";
				$("#pricegrabber-holder").html(elementImg);
				$("#pricegrabber-holder").hide();

    }, "json");
    return false;

	}
}

/** @DW - not sure if this is being used at all, leaving in for now... **/
function callback_orderdirect_times(dropdown_id, object) {

	// If this is being called from the HTB page it should receive a dropdown_id of "popup_calltime_htb"
	// and an object of the button that clicked it

	// checking to see if we're getting a string or an object. When this gets fired from a .observe it seems to send a mouseEvent which we need to avoid

	if(!Object.isString(dropdown_id)){
		dropdown_id = "popup_calltime_popup";
	}

	if(!object){
		object = this;
	}

	var val = object.value;

	if(!val){
		return false;
	}

	var rel = "";
	if (window.location.toString().indexOf("/careers") != -1) {
		rel = "../";
	} else {
		rel = "./";
	}

	new Ajax.Request(rel + "how-to-buy/get-orderdirect-times/", {
		method: "post",
		parameters: "day="+val,
		onSuccess: function(transport) {
			var $response = transport.responseJSON;
			if ($response.msg!="OK") {
				return false;
			}
			// clear dropdown
			$(dropdown_id).options.length = 0;

			if ($response.result_count > 0) {
				for (var i=0; i<$response.result_count; i++) {
					var txt = $response.txt[i];
					var val = $response.vals[i];
					$(dropdown_id).appendChild(new Element("option", {"value":val}).update(txt));
				}
			}
		}
	});
}

function correct_view() {
	if ($popup.length > 0) {
		var pos_y = 20;

		if ($(window).height() > $popup.outerHeight())
    {
			pos_y = 0 + ($(window).scrollTop() + (($(window).height() / 2) - ($popup.outerHeight()/2)));
		}
    else
    {
      $("html, body").animate({scrollTop:0}, "fast");
    }
		$popup.css('top',pos_y);
    $popup.css("left", ($("#container").outerWidth() - $popup.outerWidth())/2);
	}
}

$(window).resize(function() {
	correct_view();
});

$(window).scroll(function() {
	correct_view();
});

// event listener to add clicks to order direct buttons
$(function(){
	$("#order-direct").click(function(){
		toggle_popup("topnav");
	});

	$(".order-direct-button").click(function(){
    toggle_popup("productpage");
  });
	$(".order-direct-homepage").click(function(){
    toggle_popup("homepage");
  });
	/*$(".order-direct").click(function(){
    toggle_popup("product");
	});*/

	$(".sales-pdf").click(function(){
    window.open($(this).attr("href"), "Brochure", "toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1");
	});

  $("#order_direct_popup a.close").live("click", function() {
    hideOverlay();

    // unset $popup
    $popup = {
		length: 0
	};

    $("#order_direct_popup").fadeOut("fast");
    setTimeout(function() {
      $("#order_direct_popup").remove();
    }, 500);

    return false;
  });
});

var centerPopup = function(element) {
  if (typeof(element) == 'string') {
	element = $(element);
  }

  if (element.length == 0) {
    return false;
  }

  correct_view();

  setTimeout( function() {
    centerPopup(element);
  }, 100);

  return false;
};

var showOverlay = function() {
  if ($("#dark-overlay").length > 0) {
    $("#dark-overlay").remove();
  }

  var element = $("#container");
  if (element.length == 0) {
    element = $("#wrapper");
  }
  var offset = element.offset();

  element.append("<div id=\"dark-overlay\" />");
  $("#dark-overlay").css({ "top" : (offset.top * -1), "left" : (offset.left * -1), "width" : $(document).width(), "height" : $(document).height() });

};

var hideOverlay = function() {
  $("#dark-overlay").fadeOut("fast");
  setTimeout(function() {
    $("#dark-overlay").remove();
  }, 500);
};

$(function() {
  $("a[rel='external']").each(function(e, element) {
    $(element).attr("target", "_blank");
  });

  $("a.live-chat").click(function() {
    // TODO: change this URL to live URL
    window.open('http://89.234.28.132?campaign=default&itr_type=collab','','toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=yes');
    return false;
  });

  $("a[href='basket/terms-and-conditions/'], a[href='basket/terms-and-conditions/leather/'], a[href='basket/terms-and-conditions/fabric/']").click(function() {
    window.open(base_href + $(this).attr("href"), "Terms", "height=650,width=620,scrollbars=1");
    return false;
  });

  $("a[href='basket/free-credit/']").click(function() {
    window.open(base_href + $(this).attr("href"), "IFC", "height=650,width=620,scrollbars=1");
    return false;
  });

  // promotional updates signup
  $("form[name='promotional-updates']").submit(function(e) {
    e.preventDefault();

    var self = $(this);
    var data = self.serialize();
    // add ajax call into data
    data += "&ajax=true";

    // show loader
    self.children(".loader:first").show();
    // hide any errors
    self.find(".msg").remove();

    $.post(self.attr("action"), data, function(response) {
      // hide the loader
      self.children(".loader:first").hide();

      if (response.ERROR)
      {
        // show error message
        $("<div class=\"error msg\">"+response.ERROR+"</div>").insertAfter(self.find("label"));
      }
      else
      {
        // msg is ok!
        self.find("input").hide();
        _gaq.push(['_trackEvent', 'Newsletter Signup', 'Newsletter Signup']);

        // insert thank you message
        $("<div class=\"thankyou msg\">Thank you for signing up to our mailing list!</div>").insertAfter(self.find("label"));
      }
    }, "json");

    return false;

    setTimeout(function() {
      self.children(".field:first").children("input").remove();
      self.children(".field:first").append("<p>Thank you for signing up to our mailing list</p>");
      self.children(".loader:first").hide()
    }, 1000);
  });

  $j("input[name='name']").autocomplete({
    source: base_href + "search/autocomplete-ranges/",
    minLength: 2,
    select: function(e, ui) {
      var range_url = ui.item.url;
      var redirect_url = base_href + range_url;
      // redirect to range
      window.location = redirect_url;
      return false;
    }
  });
});

