// IE 6 FIX
ie = document.all;
if(ie){
    try{
       document.execCommand("BackgroundImageCache", false, true);
    }
    catch(err){}
}

var timerID = null;
var timerRunning = false;

function stopclock(){
    if(timerRunning)
        clearTimeout(timerID);
    timerRunning = false;
}

function startclock(){
    stopclock();
    showtime();
}

function showtime(){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    var timeValue = hours;
    timeValue  += ((minutes < 10) ? ":0" : ":") + minutes;
    timeValue  += ((seconds < 10) ? ":0" : ":") + seconds;
    document.getElementById('clock').firstChild.nodeValue = timeValue;
    timerID = setTimeout("showtime()",1000);
    timerRunning = true;
}

function isUndefined(a) {
    return typeof a == 'undefined';
}

function selections_validate(deliverto, totalcount) {
    var checkbox_choices = 0;

    for (counter = 0; counter < totalcount; counter++) {
        var elem = 'chk'+(counter+1);
        if (document.selections.elements[elem].checked) {
            checkbox_choices = checkbox_choices + 1;
        }
    }

    if (checkbox_choices < 1) {
        alert("Please tick at least one item from the list below.");
    } else {
        document.selections.action = deliverto;
        document.selections.submit();
    }
}

function selections_validate_del(deliverto, totalcount) {
    var checkbox_choices = 0;

    for (counter = 0; counter < totalcount; counter++) {
        var elem = 'chk'+(counter+1);
        if (document.selections.elements[elem].checked) {
            checkbox_choices = checkbox_choices + 1;
        }
    }

    if (checkbox_choices < 1) {
        alert("Please tick at least one item from the list below.");
    } else {
        if (confirm('Are you sure you want to delete all selected items.\nPLEASE NOTE: Any related items may be deleted!')) {
            document.selections.action = deliverto;
            document.selections.submit();
        }
    }
}

function selectall(obj) {
	obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
	if (obj.tagName.toLowerCase() != "select")
		return;
	for (var i=0; i<obj.length; i++) {
		obj[i].selected = true;
	}
}

function selectnone(obj){
	obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
	if (obj.tagName.toLowerCase() != "select")
		return;
	for (var i=0; i<obj.length; i++) {
		obj[i].selected = false;
	}
}

function selections_validate_download(deliverto, totalcount) {
    var checkbox_choices = 0;

    for (counter = 0; counter < totalcount; counter++) {
        var elem = 'chk'+(counter+1);
        if (document.selections.elements[elem].checked) {
            checkbox_choices = checkbox_choices + 1;
        }
    }

    if (checkbox_choices < 1) {
        alert("Please tick the document you would like to download.");
    } else if (checkbox_choices > 1) {
        alert("You can only download one file at a time, you have selected more than one.");
    } else {
        document.selections.action = deliverto;
        document.selections.submit();
    }
}

function selections_validate_download_nocheckboxes(deliverto, totalcount) {
    document.selections.action = deliverto;
    document.selections.submit();
}

function pfv(deliverto, getvars) {
    link = deliverto+'?'+getvars
    MM_openBrWindow(link, '', '');
}

function validate_checks(totalcount) {
   var checkbox_choices = 0;
   for (counter = 0; counter < totalcount; counter++) {
	  var elem = 'chk'+(counter+1);
	  if (document.selections.elements[elem].checked) {
		 checkbox_choices = checkbox_choices + 1;
	  }
   }
   if (checkbox_choices < 1) {
	  alert("Please tick at least one item from the list below.");
   } else {
	  document.selections.submit();
   }
}

function MM_openBrWindow(theURL, winName, features){
   window.open(theURL, winName, features);
}

function selectAll(theform, thecheckbox) {
   for(var i=0; i<50; i++) {
      if (document.selections.elements['chk'+i]) {
         document.selections.elements['chk'+i].checked = true;
      }
   }
}

function dselectAll() {
   for(var i=0; i<50; i++) {
      if (document.selections.elements['chk'+i]) {
         document.selections.elements['chk'+i].checked = false;
      }
   }
}

function checkBox(themouseevent, box, i, theclass) {
	selected_row_style = "selected";
	x = 'tr' + i;
	if(themouseevent=="click") {
		if(box.checked==true) {
			box.checked = false;
			document.getElementById(x).className =  theclass;
		} else {
			box.checked = true;
			document.getElementById(x).className =  selected_row_style;
		}
	} else if(themouseevent=="over") {
		if(box.checked==false) document.getElementById(x).className =  theclass;
	} else if(themouseevent=="out") {
		(box.checked==false) ? document.getElementById(x).className =  theclass : document.getElementById(x).className =  selected_row_style;
	} else if(themouseevent=="selectAll") {
		for(var n=0; n<51; n++) {
			thebox = box + n;
			if(document.getElementById(thebox)) {
			     document.getElementById(thebox).checked = true;
			     x = 'tr' + n;
			     document.getElementById(x).className = selected_row_style;
			}
		}
	}  else if(themouseevent=="dselectAll") {
		for(var n=0; n<51; n++) {
			thebox = box + n;
			if(document.getElementById(thebox)) {
			     document.getElementById(thebox).checked = false;
			     x = 'tr' + n;
			     (n%2==0) ? theclass = "row" : theclass = "alt";
			     document.getElementById(x).className =  theclass;
			}
		}
	}
}

document.getElementsByClassName = function(cl) {
    var retnode = [];

    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = this.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};


function printWindow() {
  	alert("Please set your printer to A4 portrait. Thank You.");
	window.print();
}

function printWindow2() {
  	alert("Please set your printer to A4 Landscape. Thank You.");
	window.print();
}

function addOption(selectbox, value, text )
{
    if(Prototype.Browser.IE) {
        var optn = document.createElement("OPTION");
        optn.text = text;
        optn.value = value;

        selectbox.options.add(optn);
    } else {
        node = selectbox;
        try {
            new Insertion.Bottom(node, '<option value="'+value+'">'+text+'</option>');
        } catch (e) {
            appendChildNodes(node, OPTION(text));
        }

    }
}

function add_new_option(box) {
    var option = prompt('Please enter your addition below:');
    //alert("adding "+option+" to "+box);
    if (option != "" && option != 'undefined' && option != null) {
        addOption(document.getElementById('id_'+box), option, option);
        document.getElementById('id_'+box).value = option;
    }
}

// this function is needed to work around
// a bug in IE related to element attributes
function hasClass(obj) {
   var result = false;
   if (obj.getAttributeNode("class") != null) {
       result = obj.getAttributeNode("class").value;
   }
   return result;
}

function stripe(id) {

  // the flag we'll use to keep track of
  // whether the current row is odd or even
  var even = false;

  // if arguments are provided to specify the colours
  // of the even & odd rows, then use the them;
  // otherwise use the following defaults:
  var evenColor = arguments[1] ? arguments[1] : "#fff";
  var oddColor = arguments[2] ? arguments[2] : "#eee";

  // obtain a reference to the desired table
  // if no such table exists, abort
  var table = document.getElementById(id);
  if (! table) { return; }

  // by definition, tables can have more than one tbody
  // element, so we'll have to get the list of child
  // &lt;tbody&gt;s
  var tbodies = table.getElementsByTagName("tbody");

  // and iterate through them...
  for (var h = 0; h < tbodies.length; h++) {

   // find all the &lt;tr&gt; elements...
    var trs = tbodies[h].getElementsByTagName("tr");

    // ... and iterate through them
    for (var i = 0; i < trs.length; i++) {

      // avoid rows that have a class attribute
      // or backgroundColor style
      if (! hasClass(trs[i]) &&
          ! trs[i].style.backgroundColor) {

        // get all the cells in this row...
        var tds = trs[i].getElementsByTagName("td");
        var ths = trs[i].getElementsByTagName("th");

        // and iterate through them...
        for (var j = 0; j < ths.length; j++) {

          var myth = ths[j];

          // avoid cells that have a class attribute
          // or backgroundColor style
          if (! hasClass(myth) &&
              ! myth.style.backgroundColor) {

            myth.style.backgroundColor =
              even ? evenColor : oddColor;

          }
        }

        // and iterate through them...
        for (var j = 0; j < tds.length; j++) {

          var mytd = tds[j];

          // avoid cells that have a class attribute
          // or backgroundColor style
          if (! hasClass(mytd) &&
              ! mytd.style.backgroundColor) {

            mytd.style.backgroundColor =
              even ? evenColor : oddColor;

          }
        }
      }
      // flip from odd to even, or vice-versa
      even =  ! even;
    }
  }
}

var postal_address = "";

function SavePostalAddress(form) {
    postal_address = form.postal_address.value;
}

function PostalToPhysical(form) {
    if (form.same_address.checked) {
        SavePostalAddress(form);
        form.postal_address.value = form.delivery_address.value;
    } else {
        form.postal_address.value = postal_address;
    }
}

function validate_del(url) {
    if (confirm('Are you sure you want to delete the selected item.\nPLEASE NOTE: Any related items may be deleted!')) {
	document.location = url;
    }
}

function textCounter(field,counter,maxlimit,linecounter) {
    var fieldWidth =  parseInt(field.style.width);
    var charcnt = field.value.length;
    if (charcnt > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
    } else {
        var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ;
        document.getElementById(counter).style.width =  parseInt((fieldWidth*percentage)/100)+"px";
        setcolor(document.getElementById(counter),percentage,"background-color");
    }
}

function validate_member_app_check(form) {
   // Must accept terms of condition
   if(document.getElementById(form).terms.checked == false) {
      alert('Please make sure you have filled in all fields and accept the terms of condition');
   }
   // Company details validation
   else if (document.getElementById(form).company_name.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_reg_number.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_trading.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_size.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_vat.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_tel.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_email.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_email_confirm.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_fax.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_postal.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).company_address.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   // Contact details validation
   else if (document.getElementById(form).contact_store_details_person.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).contact_store_details_mobile.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   // Details of Directors/Proprietors/Partners
   else if (document.getElementById(form).contact_director_details_name.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).contact_director_details_id.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).contact_proprietors_details_name.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).contact_proprietors_details_id.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).contact_partner_details_name.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).contact_partner_details_id.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   // Details of bank order
   else if (document.getElementById(form).bank_order_name.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).bank_order_address.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).bank_order_date.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).bank_order_signatory.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).bank_order_tel.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   // Details of the person's bank account
    else if (document.getElementById(form).bank_account_details_bank.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).bank_account_details_branch.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).bank_account_details_account_name.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).bank_account_details_type.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   else if (document.getElementById(form).bank_account_details_account_number.value == ""){
      alert('Please make sure you have filled in all fields');
   }
   // Submit form if all fields are filled in
   else {
      document.getElementById(form).submit();
   }
}

function submit_order_complete(form) {
   document.getElementById(form).submit();
}

function createCookie(name,value,days) {
   if (days) {
	  var date = new Date();
	  date.setTime(date.getTime()+(days*24*60*60*1000));
	  var expires = "; expires="+date.toGMTString();
   }
   else var expires = "";
   document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
	   var c = ca[i];
	   while (c.charAt(0)==' ') c = c.substring(1,c.length);
	   if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
   }
   return null;
}

function eraseCookie(name) {
   createCookie(name,"",-1);
}

function getCookie(c_name){
   if (document.cookie.length>0)
	 {
	 c_start=document.cookie.indexOf(c_name + "=");
	 if (c_start!=-1)
	   {
	   c_start=c_start + c_name.length+1;
	   c_end=document.cookie.indexOf(";",c_start);
	   if (c_end==-1) c_end=document.cookie.length;
	   return unescape(document.cookie.substring(c_start,c_end));
	   }
	 }
   return "";
}

function setCookie(c_name,value,expiredays){
   var exdate=new Date();
   exdate.setDate(exdate.getDate()+expiredays);
   document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString() ? "" : ";path=/" );
}

var browser=navigator.appName;
setCookie('browser', browser, -1)

function validate_check(form){

	if(document.getElementById(form).name.value == "") {
		alert("Please enter in a contact person.");
	} else if(document.getElementById(form).number.value == "" ){
		alert("Please enter in a cell number.");
	} else if(document.getElementById(form).email.value == "") {
		alert("Please enter in an email address.");
	} else if ((document.getElementById(form).email.value.search("@")==-1) || (document.getElementById(form).email.value.search("[.*]")==-1)) {
        alert("Please make sure that the email is filled out correctly.");
	} else if(document.getElementById(form).enquiry.value == "" ){
		alert("Please leave a comment.");
	}else{
		document.getElementById(form).submit();
	}
}

function validate_feedback(form){

	if(document.getElementById(form).name.value == "") {
		alert("Please enter in a contact person.");
	} else if(document.getElementById(form).company.value == "" ){
		alert("Please enter your company name.");
	} else if(document.getElementById(form).number.value == "" ){
		alert("Please enter in a cell number.");
	} else if(document.getElementById(form).email.value == "") {
		alert("Please enter in an email address.");
	} else if ((document.getElementById(form).email.value.search("@")==-1) || (document.getElementById(form).email.value.search("[.*]")==-1)) {
        alert("Please make sure that the email is filled out correctly.");
	} else if(document.getElementById(form).enquiry.value == "" ){
		alert("Please leave a comment.");
	}else{
		document.getElementById(form).submit();
	}
}

function buyers_check_key(form){
	
	var characterCode
	if(e && e.which){
		e = e
		characterCode = e.which
	}else{
		e = event
		characterCode = e.keyCode
	}	 
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		alert('enter is pressed');
		buyers_login(form);
		return false;
		
	}
	
 return false;
	
}

$(document).ready(function(){
	
	$("#id_buyer_login").bind("keydown", function(e) {
		
		if (e.keyCode == 13) {
				
				buyers_login('buyer_login');
				return false;
		
		}

	});
	
	$("#btn_login").click(function(){
	
		buyers_login('buyer_login');
		return false;
	
	});
	
});


function buyers_login(form) {
    if(document.buyer_login.email.value == "Email Address") {
        alert("Please Enter an email address");
        return false;
    }
    else if ((document.buyer_login.email.value.search("@")==-1) || (document.buyer_login.email.value.search("[.*]")==-1)) {
        alert("Please make sure that you fill in the email field correctly.");
        return false;
    }
    else if (document.buyer_login.password.value == "Password") {
        alert("Please Enter in your password");
        return false;
    }
    else {
        $.ajax({
            url: '/buyer-login/' + document.buyer_login.email.value + '/' + document.buyer_login.password.value + '/',
            async: false,
            success: function(data){
				if (data == ""){
					alert('Either your username and password is incorrect\n or you need to complete the registration process.');
				}
				else {
					if(data == 'buyer'){
						document.buyer_login.action = "/order/homepage/";
						document.buyer_login.submit();
					}
					else if(data == 'supplier') {
						document.buyer_login.action = "/supplier/products/summary/";
						document.buyer_login.submit();
					}
					else{
						alert('Either your username and password is incorrect\nor you need to complete the registration process.');
					}
				}
            }
        });
    }
}

function submit_before(){
    if(readCookie('unwanted') != null){
        if(confirm("Do you want to save the selected items to your order cart?")){
            $('#id_place_order').submit()
        }
    }
}

function unwanted_count(){
    unwanted = readCookie('unwanted');
    if (unwanted == null){
        createCookie('unwanted', 1, 7)
    }
}

var dialog

function check_unload(cb, md){
    if(readCookie('unwanted') != null){
	    $(document).ready(function() {
		    $dialog = $('<div></div>')
			    .html('Do you want to save the selected items to your order cart?')
			    .dialog({
				    autoOpen: false,
				    title: 'Confirmation',
    			    resizable: false,
	    		    height:140,
		    	    modal: true,
					closeOnEscape: false,
					close: function(){
					        toggle_form(document.getElementById('keywordsearch'),'visible');
					        toggle_form(document.getElementById('suppliersearch'), 'visible');
					        toggle_form(document.getElementById('orderform'), 'visible');
					},
					open: function(){
					        toggle_form(document.getElementById('keywordsearch'), 'hidden');
					        toggle_form(document.getElementById('suppliersearch'), 'hidden');
					        toggle_form(document.getElementById('orderform'), 'hidden');
					},
			        buttons: {
    			    	Cancel: function() {
		    			    $(this).dialog('close');
	    			    },
		    		    'No': function() {
							if($(this).dialog('option','md') == 'fulls'){
								val_full_search()
							}
							else if($(this).dialog('option','md') == 'keyw'){
								val_keyword_search()
							}
							else if($(this).dialog('option','md') == 'sups'){
								val_supplier_search()
							}
							else{
								window.location = $(this).dialog('option','cb')
							}
    						$(this).dialog('close');
        				},
		    		    'Yes': function() {
                            $.blockUI({
                            	message: $('img#displayBox2'),
                            	css: {
                            		top:  ($(window).height() - 153) / 2 + 'px',
                            		left: ($(window).width() - 350) / 2 + 'px',
                            		width: '350px'
                            	}
                            });
                            eraseCookie('unwanted')
                            var options = {
                            	success: function(){
                            		if($dialog.dialog('option','md') == 'fulls'){
                            			val_full_search()
                            		}
                            		else if($dialog.dialog('option','md') == 'keyw'){
                            			val_keyword_search()
                            		}
                            		else if($dialog.dialog('option','md') == 'sups'){
                            			val_supplier_search()
                            		}
                            		else{
        								window.location = $dialog.dialog('option','cb')
                            		}
                            	}
                            }
                            $('#id_place_order').ajaxSubmit(options)
			    	    	$(this).dialog('close');
			        	}
    	    		}
	    		});
    	});

        $dialog.dialog('option', 'cb', cb); 
        $dialog.dialog('option', 'md', md); 
        $dialog.dialog('open');
		/*
		// This was the original js code, replace by above, remove after complete testing!
        if(confirm("Do you want to save the selected items to your order cart?")){
		    $.blockUI({
                message: $('img#displayBox2'),
                css: {
                    top:  ($(window).height() - 153) / 2 + 'px',
                    left: ($(window).width() - 350) / 2 + 'px',
                    width: '350px'
                }
            });
            eraseCookie('unwanted')
            var options = {
                success: function(){
                    if(md == 'fulls'){
                        val_full_search()
                    }
                    else if(md == 'keyw'){
                        val_keyword_search()
                    }
                    else if(md == 'sups'){
                        val_supplier_search()
                    }
                    else{
                        window.location = cb
                    }
                }
            }
			$('#id_place_order').ajaxSubmit(options)
        }
		*/
    }
    else{
        if(md == 'fulls'){
            val_full_search()
        }
        else if(md == 'keyw'){
            val_keyword_search()
        }
        else if(md == 'sups'){
            val_supplier_search()
        }
        else{
            window.location = cb
        }
    }
}

function check_logout() {
    $.ajax({
        url: '/ajax/cart_num/',
        success: function(data){
            if (data>0) {
                if(confirm("Do you want to submit your order before you logout?")){
                    window.location = '/order/step-1/';
                } else {
                    window.location = '/log-out/';
                }
            } else {
                window.location = '/log-out/';
            }
        }
    });
}
   
function get_num_in_cart(){
   $.ajax({
		url: '/ajax/cart_num/',
		async: false,
        cache: false,
		success: function(data){
			$("#id_cart_num_a").html(data)
		}
   });
}

function validate_add_product(form) {
	if(document.getElementById(form).status.value == "")
		alert("Please choose a Status.");
	else if(document.getElementById(form).supplier_product_code.value == "")
		alert("Please Enter the Supplier Product Code.");
	else if(document.getElementById(form).name.value == "")
		alert("Please Enter the Name.");
	else if(document.getElementById(form).brand.value == "")
		alert("Please Enter the Brand.");
	else if((isNaN(document.getElementById(form).pack_size.value)) && (document.getElementById(form).pack_size.value != ""))
		alert("Please Enter the Pack Size Correctly (Numbers only).");
	else if((document.getElementById(form).unit_of_measure.value != "each") && ((document.getElementById(form).measure_amount.value == "") || (isNaN(document.getElementById(form).measure_amount.value))))
		alert("Please Enter the Measurement Amount (Numbers only).");
	else if(document.getElementById(form).unit_of_measure.value == "")
		alert("Please Select the Unit Of Measure.");
	else if(document.getElementById(form).category.value == "")
		alert("Please Enter the Category.");
	else if((document.getElementById(form).unit_cost.value == "") || (isNaN(document.getElementById(form).unit_cost.value)))
		alert("Please Enter the Unit Cost Correctly.");
	else if(document.getElementById(form).special_status.checked == true) {
        if(document.getElementById(form).special_start.value == "")
            alert("Please Enter the Special Start.");
        else if(document.getElementById(form).special_end.value == "")
            alert("Please Enter the Special End.");
            else {
                document.getElementById(form).submit();
        }
	}
    else {
		document.getElementById(form).submit();
    }
}

function new_confirmation(the_counter) {

    the_counter++;

	header = function (row) {return TR(null, map(partial(TD, {'colspan':'2','id':'hidden_con_'+the_counter}), row));}
	hidden = function (row) {return TR({'id':'afterthisconfirm_'+the_counter}, map(partial(TD, {'class':'table_hidden','width':'200px'}), row));}
	row_display = function (row) {return TR(null, map(partial(TD, {'class':'one'}), row));}
	alt_row_display = function (row) {return TR({'class':'alt','id':'afterthisconfirm_'+the_counter}, map(partial(TD, {'class':'one'}), row));}


	var newTable = TABLE({'class': 'table table_new','cellspacing':'0','cellpadding':'0'},
		THEAD({'class': 'black','id':'new_table_'+the_counter},
			header(["Order Details "+the_counter], INPUT({'id': 'hidden_con_'+the_counter, 'value': '', 'name': 'hidden_con_'+the_counter, 'class': 'vTextField width-200' }))),

			TBODY(null,map(row_display, [["Email Address", INPUT({'id': 'email_confirmation_'+the_counter, 'value': '', 'name': 'email_confirmation_'+the_counter, 'class': 'vTextField width-200 spacing2', 'onchange':"if((this.value.search('@')==-1) || (this.value.search('[.*]')==-1) || (this.value== '')){alert('Please enter a valid email.');this.value='';this.focus();this.select();}" })]])),
			TBODY(null,map(alt_row_display, [["SMS Number", INPUT({'id': 'sms_'+the_counter, 'value': '', 'name': 'sms_'+the_counter, 'class': 'vTextField width-200' ,'onchange':"if(isNaN(this.value) || this.value.search('[ ]')==1 ){alert('No spaces or characters allowed in the sms number field.');this.value='';this.select();this.focus();}",'maxlength':'12' })]]))

			 );

    i = the_counter - 1;
    elem_id = 'afterthisconfirm_' + i;
    the_elem = getElement(elem_id).parentNode.parentNode;

	MochiKit.DOM.insertSiblingNodesAfter(the_elem, newTable);

	the_elem = getElement('con_new_ref');
    setNodeAttribute(the_elem, 'onclick', "new_confirmation("+the_counter+");");

    the_elem = getElement('con_del_ref');
    setNodeAttribute(the_elem, 'onclick', "del_confirmation("+the_counter+");");

    the_elem = getElement('num_of_con');
    setNodeAttribute(the_elem, 'value', the_counter);


}

function del_confirmation(the_counter) {

    if (the_counter>1) {

        elem_id = 'hidden_con_' + (the_counter);
        the_elem = getElement(elem_id).parentNode.parentNode;
        removeElement(the_elem);

        elem_id = 'sms_' + (the_counter);
        the_elem = getElement(elem_id).parentNode.parentNode;
        removeElement(the_elem);

        elem_id = 'email_confirmation_' + (the_counter);
        the_elem = getElement(elem_id).parentNode.parentNode;
        removeElement(the_elem);

        the_counter--;
        the_elem = getElement('con_new_ref');
        setNodeAttribute(the_elem, 'onclick', "new_confirmation("+the_counter+");");

        the_elem = getElement('con_del_ref');
        setNodeAttribute(the_elem, 'onclick', "del_confirmation("+the_counter+");");

        the_elem = getElement('num_of_ref');
        setNodeAttribute(the_elem, 'value', the_counter);

    }

}

function new_director(the_counter) {

    the_counter++;

    header = function (row) {return TR(null, map(partial(TD, {'colspan':'2','id':'hidden_'+the_counter}), row));}
    row_display = function (row) {return TR({'id':'afterthis_'+the_counter}, map(partial(TD, null), row));}
    alt_row_display = function (row) {return TR({'class':'alt'}, map(partial(TD, {'class':'one'}), row));}

    var newTable = TABLE({'class': 'table table_new','cellspacing':'0','cellpadding':'0'},
    THEAD({'class': 'black','id':'new_table_'+the_counter},
        header(["Director "+the_counter], INPUT({'id': 'hidden_'+the_counter, 'value': '', 'name': 'hidden_'+the_counter, 'class': 'vTextField width-200' }))),

		TBODY(null,map(row_display, [["Name", INPUT({'id': 'director_name_'+the_counter, 'value': '', 'name': 'director_name_'+the_counter, 'class': 'vTextField width-200 spacing' })]])),
		TBODY(null,map(alt_row_display, [["Id Number", INPUT({'id': 'id_number_'+the_counter, 'value': '', 'name': 'id_number_'+the_counter, 'class': 'vTextField width-200','onchange':"if(isNaN(this.value) || this.value.search('[ ]')==1 ){alert('No spaces or characters allowed in the ID number field.');this.value='';this.select();this.focus();}" })]])),
		TBODY(null,map(row_display, [["Physical Address", TEXTAREA({'rows':'5','id': 'address_'+the_counter, 'name': 'address_'+the_counter, 'class': 'vTextField width-200',ROWS:'5' })]])),
		TBODY(null,map(alt_row_display, [["Contact Number", INPUT({'id': 'contact_number_'+the_counter, 'value': '', 'name': 'contact_number_'+the_counter, 'class': 'vTextField width-200','onchange':"if(isNaN(this.value) || this.value.search('[ ]')==1 ){alert('No spaces or characters allowed in the contact number field.');this.value='';this.select();this.focus();}",'maxlength':'12' })]])),
		TBODY(null,map(row_display, [["Email Address", INPUT({'id': 'email_'+the_counter, 'value': '', 'name': 'email_'+the_counter, 'class': 'vTextField width-200', 'onchange':"if((this.value.search('@')==-1) || (this.value.search('[.*]')==-1) || (this.value== '')){alert('Please enter a valid email.');this.value='';this.focus();this.select();}"})]]))

		);

    i = the_counter - 1;
	r = the_counter;
    elem_id = 'afterthis_' + i;
    the_elem = getElement(elem_id).parentNode.parentNode;

	MochiKit.DOM.insertSiblingNodesAfter(the_elem, newTable);

	the_elem = getElement('btn_new_ref');
    setNodeAttribute(the_elem, 'onclick', "new_director("+the_counter+");");

    the_elem = getElement('btn_del_ref');
    setNodeAttribute(the_elem, 'onclick', "del_director("+the_counter+");");

    the_elem = getElement('num_of_ref');
    setNodeAttribute(the_elem, 'value', the_counter);

}

function del_director(the_counter) {

    if (the_counter>1) {

        elem_id = 'director_name_' + (the_counter);
        the_elem = getElement(elem_id).parentNode.parentNode;
        removeElement(the_elem);

        elem_id = 'id_number_' + (the_counter);
        the_elem = getElement(elem_id).parentNode.parentNode;
        removeElement(the_elem);

        elem_id = 'address_' + (the_counter);
        the_elem = getElement(elem_id).parentNode.parentNode;
        removeElement(the_elem);

        elem_id = 'contact_number_' + (the_counter);
        the_elem = getElement(elem_id).parentNode.parentNode;
        removeElement(the_elem);

        elem_id = 'email_' + (the_counter);
        the_elem = getElement(elem_id).parentNode.parentNode;
        removeElement(the_elem);

        elem_id = 'hidden_' + (the_counter);
        the_elem = getElement(elem_id).parentNode.parentNode;
        removeElement(the_elem);


        the_counter--;
        the_elem = getElement('btn_new_ref');
        setNodeAttribute(the_elem, 'onclick', "new_director("+the_counter+");");

        the_elem = getElement('btn_del_ref');
        setNodeAttribute(the_elem, 'onclick', "del_director("+the_counter+");");

        the_elem = getElement('num_of_ref');
        setNodeAttribute(the_elem, 'value', the_counter);
    }
}

function validate_buyer_registration(form) {
   if(document.getElementById(form).company_name.value == "")
	  alert("Please Enter in the Company Name.");
   else if(document.getElementById(form).trading_as.value == "")
	  alert("Please Enter the Trading As Field.");
   else if(document.getElementById(form).delivery_address.value == "")
	  alert("Please Enter in the Physical Address.");
   else if(document.getElementById(form).province.value == "")
	  alert("Please Select a Province.");
   else if(document.getElementById(form).region.value == 0)
	  alert("Please Select a Region.");
   else if(document.getElementById(form).instore_manager.value == "")
	  alert("Please Enter the Instore Contact Person .");
   else if(document.getElementById(form).instore_contact.value == "")
	  alert("Please Enter Instore Contact number.");
   else if(document.getElementById(form).instore_fax.value == "")
	  alert("Please Enter Instore Fax number.");
   else if(document.getElementById(form).instore_email.value == "") {
	  alert("Please Enter an Instore  E-mail Address");
   } else if ((document.getElementById(form).instore_email.value.search("@")==-1) || (document.getElementById(form).instore_email.value.search("[.*]")==-1)) {
	  alert("Please make sure that you fill in the Instore E-mail field correctly.");}
   else if(document.getElementById(form).email_confirmation_1.value == "" && document.getElementById(form).page.value == 'Add' ) {
	  alert("Please Enter an confirmation Email Address");
   } else if (((document.getElementById(form).email_confirmation_1.value.search("@")==-1) && document.getElementById(form).page.value == 'Add' ) || ((document.getElementById(form).email_confirmation_1.value.search("[.*]")==-1) && document.getElementById(form).page.value == 'Add' )) {
	  alert("Please make sure that you fill in the confirmation Email field correctly.");}
   else{
	  if(document.getElementById(form).same_address.checked == true ){
		 document.getElementById(form).postal_address.value = document.getElementById(form).delivery_address.value;
	  }
	  if(document.getElementById(form).page.value == 'Add'){
		 $.ajax({
			url: '/buyer-verify/' + document.getElementById(form).img_text.value + '/' + document.getElementById(form).imghash.value + '/',
			async: false,
			success: function(data){
			   if(data){
				  $.ajax({
					 url: '/supplier-customer-registration/' + document.customer_form.instore_email.value + '/' + document.getElementById(form).vat_number.value   + '/',
					 async: false,
					 success: function(data){
						if (data == ""){
						   document.getElementById(form).submit();
						}
						else {
						   if(document.getElementById(form).mode.value=='new_buyer'){
							  /* Buyer registering themselves */
							  if (confirm(data +' already Exists of the system? Press OK to go to home page\nPLEASE NOTE: You can cancel and alter the instore email to a different email address!')) {
								 document.getElementById(form).action = '/';
								 document.getElementById(form).submit();
							  }
						   }
						   else{
							  /* suppliers registering a buyer */
							  if (confirm('Buyer Already Exists of the system?\nDo you want to add this Buyer as your customer\nPLEASE NOTE: You can cancel and alter the instore email to a different email address!')) {
								 document.getElementById(form).action = '/supplier-customer-new-registration/';
								 document.getElementById(form).submit();
							  }
						   }
						}
					 }
				  });
			   }
			   else{
				  alert('Please double check the verification code.');
				  return false;
			   }
			}
		 });
	  }
	  else{
		 document.getElementById(form).submit();
	  }
   }
}

function validate_supplier_customer(form) {
	if(document.getElementById(form).company_name.value == "")
        alert("Please Enter in the Company Name.");
	else if(document.getElementById(form).trading_as.value == "")
        alert("Please Enter the Trading As Field.");
	else if(document.getElementById(form).delivery_address.value == "")
        alert("Please Enter in the Physical Address.");
	else if(document.getElementById(form).province.value == "")
        alert("Please Select a Province.");
	else if(document.getElementById(form).region.value == 0)
        alert("Please Select a Region.");
	else if(document.getElementById(form).instore_manager.value == "")
        alert("Please Enter the Instore Contact Person .");
	else if(document.getElementById(form).instore_contact.value == "")
        alert("Please Enter Instore Contact number.");
	else if(document.getElementById(form).instore_fax.value == "")
        alert("Please Enter Instore Fax number.");
   	else if(document.getElementById(form).instore_email.value == "")
        alert("Please Enter an Instore  E-mail Address");
    else if ((document.getElementById(form).instore_email.value.search("@")==-1) || (document.getElementById(form).instore_email.value.search("[.*]")==-1)) {
        alert("Please make sure that you fill in the Instore E-mail field correctly.");}
   	//else if(document.getElementById(form).email_confirmation_1.value == "" && document.getElementById(form).page.value == 'Add' )
    //    alert("Please Enter a confirmation Email Address");
	//else if (((document.getElementById(form).email_confirmation_1.value.search("@")==-1) && document.getElementById(form).page.value == 'Add' ) || ((document.getElementById(form).email_confirmation_1.value.search("[.*]")==-1) && document.getElementById(form).page.value == 'Add' ))
    //    alert("Please make sure that you fill in the confirmation Email field correctly.");
    else {
        if(document.getElementById(form).same_address.checked == true ){
            document.getElementById(form).postal_address.value = document.getElementById(form).delivery_address.value;
        }
        if(document.getElementById(form).page.value == 'Add'){

            $.ajax({
                url: '/supplier-customer-registration/' + document.customer_form.instore_email.value + '/',
                async: false,
                success: function(data){
                    if ( data == ""){
                        document.getElementById(form).submit();
                    }
                    else {
                        if(document.getElementById(form).mode.value=='new_buyer'){
                            /* Buyer registering themselves */
                            if (confirm(data +' already exists? Press OK to go to home page\nPLEASE NOTE: You can cancel and alter the instore email to a different email address!')) {
                                document.getElementById(form).action = '/';
                                document.getElementById(form).submit();
                            }
                        }
                        else{
                            /* suppliers registering a buyer */
                            document.getElementById(form).action = '/supplier-customer-new-registration/';
                            document.getElementById(form).submit();
                        }
                    }
                }
            });
        }
        else{
            document.getElementById(form).submit();
        }
    }
}

function confirmation_delete(form) {
    if (confirm('Are you sure you want to delete '+ document.getElementById(form).edit_email.value  +' from the Confirmation Details List?')) {
        document.getElementById(form).mode.value = 'delete_confirmation';
        document.getElementById(form).submit();
    }
}

function validate_confirmation_add(form) {

	if(document.getElementById(form).edit_email.value == "") {
		alert("Please Enter an E-mail Address");
	} else if ((document.getElementById(form).edit_email.value.search("@")==-1) || (document.getElementById(form).edit_email.value.search("[.*]")==-1)) {
        alert("Please make sure that you fill in the email field correctly.");
	} else {
		document.getElementById(form).mode.value = 'update_confirmation';
		document.getElementById(form).submit();
	}
}


function director_delete(form) {

        if (confirm('Are you sure you want to delete '+ document.getElementById(form).edit_director_name.value  +' from the Director List?')) {
		  document.getElementById(form).mode.value = 'delete';
		  document.getElementById(form).submit();
        }

}
function validate_director_add(form) {

	if (document.getElementById(form).edit_director_name.value == "") {
		alert("Please Enter a Name");
	} else if(document.getElementById(form).id_number.value == "") {
		alert("Please Enter an ID Number");
	} else if(document.getElementById(form).contact_number.value == "") {
		alert("Please Enter a Cell Number");
	} else if(document.getElementById(form).email.value == "") {
		alert("Please Enter an E-mail Address");
	} else if ((document.getElementById(form).email.value.search("@")==-1) || (document.getElementById(form).email.value.search("[.*]")==-1)) {
        alert("Please make sure that you fill in the email field correctly.");
	} else {
		document.getElementById(form).mode.value = 'update_director';
		document.getElementById(form).submit();
	}
}

function check_out_of_stock(form){
	if(document.getElementById(form).out_of_stock.checked==false){
		document.getElementById(form).special_status.disabled=false;
		document.getElementById(form).special_start.disabled=false;
		document.getElementById(form).special_end.disabled=false;
		document.getElementById(form).description.disabled=false;
	}
	if(document.getElementById(form).special_status.checked==false){
		document.getElementById(form).special_status.disabled=false;
		document.getElementById(form).special_start.disabled=true;
		document.getElementById(form).special_end.disabled=true;
		document.getElementById(form).description.disabled=true;
	}
}
function validate_out_of_stock(form){
	if(document.getElementById(form).out_of_stock.checked==true){
		document.getElementById(form).special_status.disabled=true;
		document.getElementById(form).special_status.checked=false;
		document.getElementById(form).special_start.disabled=true;
		document.getElementById(form).special_end.disabled=true;
		document.getElementById(form).description.disabled=true;
		document.getElementById(form).special_start.value='';
		document.getElementById(form).special_end.value='';
	}else{
		document.getElementById(form).special_status.disabled=false;
		document.getElementById(form).special_start.disabled=true;
		document.getElementById(form).special_end.disabled=true;
	}
}

function add_to_favourites(id, email, ask) {
   if (ask == 'yes'){
	  if (confirm('Some of the Items are not in your Order Sheet.\nPLEASE NOTE: Do you want to add them now!')) {
		 $.ajax({
			url: '/add-to-favourites/' + id + '/' + email + '/',
			async: false,
			success: function(data){
			   if(data){
				  alert('Successfully added '+ data + ' to My Order Sheet.');
			   }
			   else{
				  do_nothing = '';
			   }
			}
		 });
	  }
   }
}

function add_scheduled(id, email){
	pass
}

function add_favorite(id){
    $.ajax({
        url: '/ajax/add-favs/' + id + '/',
        async: false,
        success: function(data){
            if(data){
                alert('Successfully added '+ data + ' to My Order Sheet.')
            }
            else{
                alert('This product is already saved in your Order Sheet.')
            }
        }
    });
}

function update_order_cart(id, amount){
    $.ajax({
        url: '/update-cart/' + id + '/' + amount + '/',
        async: false
    });
}

function check_password(){

    var password = document.change_password.password.value;
    var password_confirm = document.change_password.confirm_password.value;

    if(password != password_confirm){
        alert('Please make sure Password and Confirm Password are the same.');
    }
    else{
        document.getElementById('id_change_password').submit()
    }
}

function step_2_check(form){

	if (document.getElementById(form).your_name.value == "") {
		alert("Please Enter in your Name");
	} else if(document.getElementById(form).your_contact_number.value == "") {
		alert("Please Enter in your contact Number");
	} else {
		document.getElementById(form).submit();
	}
}
function step_3_check(form){

	if (document.getElementById(form).terms.checked == false) {
		alert("Please accept terms and conditions.");
	} else {
		document.getElementById(form).submit();
	}
}

function ie_detect(){
	var isIE = false;
	var isIE6 = false;
	var isIE7 = false;
	if(isIE || isIE6 || isIE7){
		value = 'true';
		return value;
	}
}

function validate_reject(form){
	if(document.getElementById(form).reasons.value == ""){
		alert("Please Enter A Reason For Rejecting This Order.");
	}
	else{
	   document.getElementById(form).submit();
	}
}

// if you would like to create the order include redirect_to_cart in the call to this function
// if redirect_to_cart is not sent, by default the cart will be updated, but it will not be
function order_button(redirect_to_cart) {
    if(!redirect_to_cart)
        redirect_to_cart = false;

    $.blockUI({
        message: $('img#displayBox2'),
        css: {
            top:  ($(window).height() - 153) /2 + 'px',
            left: ($(window).width() - 350) /2 + 'px',
            width: '350px'
        }
    });
    eraseCookie('unwanted');

    if (redirect_to_cart==true)
        document.place_order.redirect_to_cart.value = "True";

    document.place_order.submit()
}

function disableEnterKey(e){
	var key;
	if(window.event){
		key = window.event.keyCode; //IE
	}
	else{
		key = e.which; //firefox
	}
	return (key != 13)
}

function val_full_search(showUI){
   if(document.getElementById('id_supplier').value == ''){
        alert('Please select a supplier to continue.');
    }
    else if(document.getElementById('id_category').value == ''){
        alert('Please select a category to continue.');
    }
    else if(document.getElementById('id_sub_category').value == ''){
        alert('Please select a sub category to continue.');
    }
    else{
        $("#id_product_search").submit();
        if(showUI == true){
            $.blockUI({
                message: $('img#displayBox'),
                css: {
                    top:  ($(window).height() - 153) /2 + 'px',
                    left: ($(window).width() - 350) /2 + 'px',
                    width: '350px'
                }
            });
        }
    }
}

function val_keyword_search(){
	if(document.getElementById('keyword').value == ''){
		alert('Please enter a keyword to continue.')
	}
	else{
		document.getElementById('keywordsearch').submit()
		$.blockUI({
			message: $('img#displayBox'),
			css: {
				top:  ($(window).height() - 153) /2 + 'px',
				left: ($(window).width() - 350) /2 + 'px',
				width: '350px'
			}
		})
	}
}

function val_supplier_search(){
	if(document.getElementById('supplier').value == ''){
		alert('Please select a supplier to continue.')
	}
	else{
		document.getElementById('suppliersearch').submit()
		$.blockUI({
			message: $('img#displayBox'),
			css: {
				top:  ($(window).height() - 153) /2 + 'px',
				left: ($(window).width() - 350) /2 + 'px',
				width: '350px'
			}
		})
	}
}

function qty_val(fid){
    if($("#"+fid).val() != ''){
        if((isNaN($("#"+fid).val())) || ($('#'+fid).val() > 999) || ($('#'+fid).val() == 0) || ($('#'+fid).val().search(".") == -1)){
            alert('Please make sure that you entered a number between 1 and 999.');
            $('#'+fid).val('');
        }
        else{
            unwanted_count()
        }
    }
}

function val_delete_order(id){
    if(confirm('Are you sure you want to delete this item from your order cart?')){
        window.location = '/order/del-item/' + id + '/'
    }
}

function val_delete_fav(id, buyer){
    if(confirm('Are you sure you want to delete this item from your Order Sheet?')){
        window.location = '/order/del-fav/' + id + '/' + buyer + '/'
    }
}

function submit_order_favs(fav_list){
    if(confirm('Some of these items are not yet in your Order Sheet. Would you like to add them now?')){
        $.blockUI({
            message: $('img#displayBox2'),
            css: {
                top:  ($(window).height() - 153) /2 + 'px',
                left: ($(window).width() - 350) /2 + 'px',
                width: '350px'
            }
        });
        $.ajax({
			url: '/ajax/add-favs-bulk/' + fav_list + '/',
			async: false
		});
    }
    eraseCookie('unwanted');
    document.place_order.submit()
}

function del_price_list(){
    var current_pl = $("#id_price_list").val()
    if(current_pl != ''){
        if(confirm('Are you sure you want to delete this Price List?')){
            $.ajax({
                url: '/ajax/del-plist/' + current_pl + '/',
                async: false,
                cache: false,
                success: function(data){
                    if(data == 'done'){
                        window.location = '?price_list='
                    }
                    else{
                        alert('There are still some buyers associated with this pricelist. Please reassign them first.')
                    }
                }
            });
        }
    }
}

function validate_add_pricelist(){
    alert('You have no products yet. Please add at least one product to continue.')
}

// Clear field with an initial value
function clear_field(mode, field, init){
    if(mode == 'focus' && $('#'+field).val() == init){
        ini_val = $('#'+field).val()
        $('#'+field).val('')
    }
    else{
        if($('#'+field).val() == ''){
            $('#'+field).val(init)
        }
    }
}

function add_price_list_ajax(value){
	$.ajax({
		url: '/supplier/price-lists/add/' + value + '/',
		async: false,
		success: function(data){
            if(data){
               d_array = data.split("~");
                if(d_array[0] == 'done'){
                    alert(d_array[1] + " has been successfully added.\nPlease use the Bulk Price Adjustment Tool to adjust prices.");
                    window.location = '/supplier/price-lists/summary/?price_list='+d_array[1];
                }
                else if(d_array[0] == 'name'){
                    alert("The Name: " + d_array[1] + " is already in use. Please try again.");
                }
            }
		}
	});
}

function toggle_form(theform, toggle_visible) {
    // toggle_visible possible options : hidden / visible
	//try {
	    if (document.all || document.getElementById) {
	        for (i = 0; i < theform.length; i++) {
	            var tempobj = theform.elements[i];
	            //if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
	                tempobj.style.visibility = toggle_visible;
	            //}
	            return true;
	        }
		}	
        else {
	            alert('failed');
	    }
	//}
	//catch(e) {
	//            alert('failed catch');
	//}
		
}