function loadFeedbackForm(sender) {
  if(document.getElementById("feedbackform") == null) $("body").append('<div id="feedbackform" class="hidden"></div>');
  $.ajax({
	  type: "POST",
	  url: sender.href,
	  cache: false,
	  async: false,
	  data: "",
	  success: function(html){
        $("#feedbackform").html(html);
        tb_show(sender.title, "#TB_inline?height=500&width=600&inlineId=feedbackform", null);
      }
  });
  return false;
}

function trim(value) {
	return value.replace(/^\s*([\S\s]*?)\s*$/, '$1');
}

function checkEmailValid(email) {
var text = $.ajax({
    type: "POST",
    url: "/suppliers/checkIsEmalValid",
    cache: false,
    async: false,
    dataType: "text",
    data: "email="+email
  }).responseText;
  return text=='OK';
}

function checkFeedbackForm(form) {
//var form = sender.form;
  if(form == null) form = document.getElementById("feedback_form");
  for(index=0; index<form.elements.length; index++) if(form.elements[index].type == "text" || form.elements[index].type == "select-one") form.elements[index].style.backgroundColor = "";
  if(form.sender != null && trim(form.sender.value) == '') {
	  form.sender.style.backgroundColor = "#ffbbbb";
	  form.sender.focus();
	  alert("Full name required");
	  return false;
  }
  if(form.from != null) {
	  if(trim(form.from.value) == '') {
  	  form.from.style.backgroundColor = "#ffbbbb";
	    form.from.focus();
	    alert("E-mail address required");
  	  return false;
    } else {
	    if(!checkEmailValid(trim(form.from.value))) {
		    form.from.style.backgroundColor = "#ffbbbb";
  		  form.from.focus();
	  	  alert("Invalid E-mail address");
		    return false;
  	  }
    }
  }
  if(form.jobtitle != null && trim(form.jobtitle.value) == '') {
	  form.jobtitle.style.backgroundColor = "#ffbbbb";
	  form.jobtitle.focus();
	  alert("Job Title required");
	  return false;
  }
  if(form.how_did_hear != null) {
	  if(trim(form.how_did_hear.value) == '' || (trim(form.how_did_hear.value) == 'y' && trim(form.how_did_hear_custom.value) == '')) {
  	  form.how_did_hear.style.backgroundColor = "#ffbbbb";
  	  form.how_did_hear_custom.style.backgroundColor = "#ffbbbb";
	    form.how_did_hear.focus();
	    alert("Please lect How did you hear about us");
	    return false;
    }
  }
  if(form.country != null && trim(form.country.value) == '') {
	  form.country.style.backgroundColor = "#ffbbbb";
	  form.country.focus();
	  alert("Please select a Country");
	  return false;
  }
  if(trim(form.subject.value) == '') {
	  form.subject.style.backgroundColor = "#ffbbbb";
	  form.subject.focus();
	  alert("Please select a Topic");
	  return false;
  }
  if(trim(form.message.value) == '') {
	  form.message.style.backgroundColor = "#ffbbbb";
	  form.message.focus();
	  alert("Comments required");
	  return false;
  }
  if(form.captcha != null && trim(form.captcha.value) == '') {
	  form.captcha.style.backgroundColor = "#ffbbbb";
	  form.captcha.focus();
	  alert("Please input the word on the picture");
	  return false;
  }
  var dataString = "";
  for(index=0; index<form.elements.length; index++) dataString += form.elements[index].name+"="+form.elements[index].value+"&";
  $.ajax({
    type: "POST",
    url: form.action,
    cache: false,
    async: true,
    dataType: "text",
    data: dataString,
    beforeSend: function (XMLHttpRequest) {
	  var thefeedbackform = document.getElementById("thefeedbackform");
	  var sending = document.getElementById("sending");
	  sending.style.height = thefeedbackform.offsetHeight+"px";
	  $("#thefeedbackform").hide();
	  $("#sending").show();
    },
    success: function(text){
	  $("#sending").hide();
	  if(!isNaN(text)) {
		  $("#sp_email_id").html(text);
		  $("#justsent").show();
	  }
	  else {
		  alert(text);
	  }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#sending").hide();
      alert("Form submission error. Please retry");
	  $("#thefeedbackform").show();
    }
  });

  return false;
}

function loadContactSupplierForm(sender) {
  if(document.getElementById("contact_supplier_form") == null) $("body").append('<div id="contact_supplier_form" class="hidden"></div>');
  $.ajax({
    type: "GET",
    url: sender.href,
    cache: false,
    async: false,
    data: "",
    success: function(html){
      $("#contact_supplier_form").html(html);
      tb_show(sender.title, "#TB_inline?height=320&width=450&inlineId=contact_supplier_form", null);
      var form = document.getElementById("ContactSupplierForm");
      if(form != null) {
   	    form.subject.focus();
      }
    }
  });
  return false;
}

function checkContactSupplierForm(form) {
  if(form == null) form = document.getElementById("ContactSupplierForm");
  for(index=0; index<form.elements.length; index++) if(form.elements[index].type == "text" || form.elements[index].type == "select-one") form.elements[index].style.backgroundColor = "";

  if(trim(form.subject.value) == '') {
    form.subject.style.backgroundColor = "#ffbbbb";
    form.subject.focus();
    alert("Subject required");
    return false;
  }
  if(trim(form.message.value) == '') {
    form.message.style.backgroundColor = "#ffbbbb";
    form.message.focus();
    alert("Message required");
    return false;
  }
  var dataString = "";
  for(index=0; index<form.elements.length; index++) dataString += form.elements[index].name+"="+form.elements[index].value+"&";
  $.ajax({
    type: "POST",
    url: form.action,
    cache: false,
    async: true,
    dataType: "text",
    data: dataString,
    beforeSend: function (XMLHttpRequest) {
	  var the_contact_supplier_form = document.getElementById("the_contact_supplier_form");
	  var sending = document.getElementById("the_contact_supplier_form_sending");
	  sending.style.height = the_contact_supplier_form.offsetHeight+"px";
	  $("#the_contact_supplier_form").hide();
	  $("#the_contact_supplier_form_sending").show();
    },
    success: function(text){
	  $("#the_contact_supplier_form_sending").hide();
	  if(text=="OK") {
        $("#the_contact_supplier_form_justsent").show();
	  } else {
        $("#the_contact_supplier_form").show();
        alert(text);
	  }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#the_contact_supplier_form_sending").hide();
      alert("Form submission error. Please retry");
	  $("#the_contact_supplier_form").show();
    }
  });

  return false;
}

function tabOnClick() {
var sender = this;
if(sender.getAttribute("rel") != null && sender.getAttribute("rel") == "follow") {
  return true;
}
if(sender.getAttribute("tab") == null) {
  var load_frame = false;
  $.ajax({
    type: "GET",
    url: sender.href.replace("suppliers", "suppliers/show_tab"),
    cache: false,
    async: true,
    dataType: "text",
    beforeSend: function (XMLHttpRequest) {
      $("#the_tab").hide();
      $("#_profile_tabs_").addClass("loading");
    },
    success: function(text){
  	  $("ul.smalltabs a").removeClass("selected");
  	  $("#the_tab").html(text).show();
  	  $("#_profile_tabs_").removeClass("loading");
  	  $(sender).addClass("selected");
  	  $("a.about_nontab").click(aboutNontabClick);
  	  $(".product_promotion a.product_category_menu").click(onCategoryClick);
  	  $("a.product_link").click(onProductClick);
  	  tb_init('#the_tab a.thickbox');
  	  load_frame = true;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
	    $("#the_tab").show();
	    $("#_profile_tabs_").removeClass("loading");
    }
  });
  display_ga(sender.href);
} else {
  $("div.tabcontent div.simpletab").hide();
  $("div.tabcontent #tab_"+sender.getAttribute("tab")).show();
  $("ul.smalltabs a").removeClass("selected");
  $(sender).addClass("selected");
}
  return false;
}

function display_ga(uri) {
  try{pageTracker._trackPageview(uri);} catch(e) {
    if (document.getElementById("tab_hidden_frame") === null) {
      $("body").append("<iframe id='tab_hidden_frame' style='display: none;'></iframe>");
    }
    $("#tab_hidden_frame").attr("src", uri+"?async=1");
  }
  return false;
}

function onProductClickCommon(uri){
  $.ajax({
    type: "GET",
    url: uri,
    cache: false,
    async: true,
    dataType: "text",
    beforeSend: function (XMLHttpRequest) {
	  $("#the_tab").hide();
	  $("#_profile_tabs_").addClass("loading");
    },
    success: function(text){
  	  $("#the_tab").html(text).show();
      $(".products").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
        scroll: 2,
        visible: 10,
        start: 0,
        circular: false
	    });
	    $(".all_products_container li a").click(onProductClick);
	    $("#_profile_tabs_").removeClass("loading");
	    $("ul.smalltabs a").removeClass("selected");
	    $("ul.smalltabs a[href$=products.html]").addClass("selected");
	    tb_init('#the_tab a.thickbox');
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
	    $("#the_tab").show();
	    $("#_profile_tabs_").removeClass("loading");
    }
  });
  return false;
}

function onProductClick() {
var sender = this;
  onProductClickCommon(sender.href.replace("/product/", "/show_product_page/"));
  display_ga(sender.href);
  return false;
}

function onCategoryClick() {
var sender = this;
  onProductClickCommon(sender.href.replace("/category/", "/show_product_category_page/"));
  display_ga(sender.href);
  return false;
}

function aboutNontabClick() {
  $("ul.smalltabs a[href$=about.html]").click();
  return false;
}

function goPreviousTab(sender) {
var tab = $("ul.smalltabs a.selected").attr("tab");
var last = $("ul.smalltabs a:last").attr("tab");
  if(tab > 0) {
    tab--;
    $("ul.smalltabs a[tab="+tab+"]").click();
  }
  if(tab==0) sender.disabled = true;
  if(tab < last) sender.form.next.disabled = false;
  return false;
}

function goNextTab(sender) {
var last = $("ul.smalltabs a:last").attr("tab");
var tab = $("ul.smalltabs a.selected").attr("tab");
  if(tab < last) {
    tab++;
    $("ul.smalltabs a[tab="+tab+"]").click();
  }
  if(tab >= last) sender.disabled = true;
  if(tab>0) sender.form.previous.disabled = false;
  return false;
}

function initServiceOrdering() {
  $("#order_service_form").ajaxForm({
    clearForm: false,
    dataType: "html",
    beforeSubmit: function(formData, jqForm, options) {
      var success = true;
      var form = jqForm[0];
      messages = new Array();
      for (var i=0; i < formData.length; i++) {
        var element = form.elements[formData[i].name];
        if(element.name == "how_did_hear" || element.name == "how_did_hear_custom") {
          if(element.name == "how_did_hear" && element.value == "y" && trim(form.elements["how_did_hear_custom"].value) == "") {
            messages.push("You should fill in " + element.title);
            success = false;
            continue;
          }
        } 
        if (!formData[i].value && element.title != "") {
          messages.push("You should fill in " + element.title);
          success = false;
        } else {
          if(element.name == "from" && !checkEmailValid(formData[i].value)) {
            messages.push("Invalid " + element.title);
            success = false;
          }
        }
      }
      if(success) {
        $("#order_service_form").hide().parent().addClass("small_loading");
      } else {
        $("#error_messages ul").html("<li>"+messages.join("</li><li>")+"</li>");
        $("#theorderservice").slideUp("slow");
        $("#error_messages").slideDown("slow");
      }
      return success;
    },
    success: function(data) {
      var parent = $("#order_service_form").parent().removeClass("small_loading");
      if(data.substring(0, 7) == "http://") {
        var iframe = '<iframe id="iframesecure" src="'+data+'" class="hidden"></iframe>';
        parent.html(iframe);
        $("#iframesecure").css({background: "none", border: "none", width: parent.width()+"px", height: parent.height()+"px"}).show();
      } else parent.html(data);
    }
  });
  $(function() {
    $('.date-pick').datePicker();
    $('#retry_link').click(function (){
      $("#error_messages").slideUp("slow");
      $("#theorderservice").slideDown("slow");
      return false;
    });
  });
}

$(document).ready(function() {
var sub_body = document.getElementById("sub_body");
var index_left = document.getElementById("index_left");
var sub_body_left = document.getElementById("sub_body_left");
var sub_body_center = document.getElementById("sub_body_center");
var sub_body_right = document.getElementById("sub_body_right");
var height = 0;
  if(index_left != null) height = Math.max(height, index_left.offsetHeight);
  if(sub_body_left != null) height = Math.max(height, sub_body_left.offsetHeight);
  if(sub_body_center != null) height = Math.max(height, sub_body_center.offsetHeight);
  if(sub_body_right != null) height = Math.max(height, sub_body_right.offsetHeight);
  height = height+50+"px";
  if(index_left != null) index_left.style.minHeight = height;
  if(sub_body_left != null) sub_body_left.style.minHeight = height;
  if(sub_body_center != null) sub_body_center.style.minHeight = height;
  if(sub_body_right != null) sub_body_right.style.minHeight = height;
  
  $("ul.smalltabs a").click(tabOnClick);
  $("a.about_nontab").click(aboutNontabClick);
  $("a.product_category_menu").click(onCategoryClick);
  $("a.product_link").click(onProductClick);
});

