
$(document).ready(function() {
	//Initiating array structure for menu
	$('#pqs_year').load("/lm/ajax/script.php?act=getPubYears");
	$('#pqs_year').change(function() {
		$('#pqs_section').empty();
		$('#pqs_section').append("<option value=''>Select Section</option>");
		$('#pqs_report').empty();
		$('#pqs_report').append("<option value='' selected>Select Country / Area</option>");
		$('#pqs_type').empty();
		$('#pqs_type').load("/lm/ajax/script.php?act=getPubTypes&pubYear=" + $('#pqs_year').val());
	});
	$('#pqs_type').change(function() {
		$('#pqs_report').load("/lm/ajax/script.php?act=getPubReport&pubYear=" + $('#pqs_year').val() + "&pubType=" + $('#pqs_type').val());
	});
	$('#pqs_report').change(function() {
		$('#pqs_section').empty();
		$('#pqs_section').load("/lm/ajax/script.php?act=getPubSection&pubYear=" + $('#pqs_year').val() +  "&pubType=" + $('#pqs_type').val() + "&pubReport=" + $('#pqs_report').val());
	});
	$("#statepartieslink").load("/getmbtstates");
	//$("dd").hide();
	$("dt a").click(
		function(){
			if($(this).parent().parent().find("li").size() == 0){
				window.location = $(this).attr("href");
			}
			else{
				$("img").each( function(index) {
					if($(this).attr("id") == "expandimage"){
						$(this).attr("src", "/design/lm/images/expand_icon.png")
					}
				} );
					
				//$("#expand_image").attr("src", "/design/lm/images/expand_icon.png");
				$(this).parent().parent().find("#expandimage").attr("src", "/design/lm/images/collapse_icon.png"); //  = "/design/lm/images/collapse_icon.png";
				$("dd:visible").slideUp("slow");
				if(last_clicked != $(this).parent().parent().find("dt").attr("id") || expand_flag == true){
					$(this).parent().next().slideDown("slow");
					last_clicked = $(this).parent().parent().find("dt").attr("id");
					expand_flag = false;
				}
				else{
					expand_flag = true;
					$(this).find("img").attr("src", "/design/lm/images/expand_icon.png");
				}
			}
			return false;
		}
	);
});

function formHandler(form){
var year = document.form.year.value;
var URL = "/lm/"+document.form.year.value+"/"+document.form.country.options[document.form.country.selectedIndex].value+".html"; 
//document.form.action.value 
// 
window.location.href = URL;
}

// Remove leading and trailing whitespace from a form element
function stripper (ret) {
  ret = "" + ret;
  var max = ret.length + 1;
  if (ret.length) {
    var ret2 = ret;
    for (var i = 0; i < ret.length; i++) {
      if (ret.charAt(i) == " " || ret.charAt(i) == "\n" || 
          ret.charAt(i) == "\t" || ret.charAt(i) == "\r" ) {
        ret2 = ret.substring(i+1, ret.length);
      } else {
        i = max;
        break;
      }
    }
    ret = ret2;
    for (var j = ret.length - 1; j >= 0; j--) {
      if (ret.charAt(j) != " ") {
        ret = ret.substring(0, j + 1);
        j = -1;
        break;
      }
    }
  }
  return ret;
}

// Generic function to test a form field for a value, and
// alert a message if it is blank. Return true if its bad.
function checkField(f, e, txt) {
  if (f) {
    var el;
    if (document.getElementById && document.getElementById(e) && document.getElementById(e).getAttribute("id")==e) {
      el = document.getElementById(e);
    } else if (f.elements[e]) {
      el = f.elements[e];
    }
    if (!el) { return true; }
    if (el.type == "select-one") {
      if (el.selectedIndex < 0 ||
          el.options[el.selectedIndex].value == "") {
         alert(txt);
         el.focus();
       } else {
         return false;
       }
    } else {
      if (el.value) { 
        el.value = stripper(el.value);
      }
      if (el.value == "") {
        el.focus();
        alert(txt);
      } else {
        return false;
      }
    }
  }
  return true;
}


function checkEmail(f, e, txt) {
  if (f) {
    var el;
    if (document.getElementById && document.getElementById(e)) {
      el = document.getElementById(e);
    } else if (f.elements[e]) {
      el = f.elements[e];
    }
    if (!el) { return true; }

    var val = el.value;
    var at = val.indexOf('@');
    if (at <= 0) {
      alert(txt);
      el.focus();
      return true;
    }
    var name = val.substring(0, at);
    var domain = val.substring(at + 1, val.length);
    if (domain.indexOf('.') <= 0) {
       alert(txt);
       return true;
    }
    return false;
  }
}

// Open the product popup window
function openLMCartWindow(nodeid) {
  var w = window.open("/index.php/content/view/popup/" + nodeid, "lmcart", "toolbar=0,location=0,menubar=0,resizable=yes,scrollbars=yes,width=350,height=500", false);
  w.focus();
}

function checkLMBasketEntry(f) {
  if (!f.elements['BasketItemCount']) {
    return false;
  }
  var v = f.elements['BasketItemCount'].value;
  if (!v) { return false; }
  if (isNaN(v)) { return false; }
  if (v == "-0") { return false; }
  v = parseInt(v);
  if (v < 0) { return false; }
  f.elements['BasketItemCount'].value = v;
  return true;
}

// From the order page, upate a product quantity and send it over to the shopping cart
function updateLMBasket(objid) {
  var f = document.forms['lmupdatebasket'];
  var bf = document.forms['lmbasketitem' + objid];
  if (!f || !bf) { return void(0); }
  var outVal = bf.elements['BasketItemCount'].value;
  if (!outVal) { outVal = 0; }
  var v = false;
  if (document.getElementById) {
    v = document.getElementById('lmupdatebasketitem'+objid);
  } else {
  }
  if (!v) { return void(0); }
  if (isNaN(outVal)) {
    return void(0);
  } else if (outVal < 0) {
    return void(0);
  }
  v.value = outVal;
  f.submit();
}

// Given a basket ID, make its text input active
function editLMBasketEntry(basketid) {
  var f = document.forms['lmbasketform'];
  if (!f) { return false; }
  var i = f.elements["lmbasketentry"+basketid];
  if (!i) { return false; }
  i.disabled = false;
  i.focus();
  i.select();
}

function updateLMBasketEntry(basketid) {
  var f = document.forms['lmbasketform'];
  if (!f) { return void(0); }
  var i = f.elements["lmbasketentry"+basketid];
  if (!i) { return void(0); }
  var h = f.elements['lmbaskethidden'+basketid];
  if (!h) { return void(0); }
  h.value = i.value;
  if (!h.value) { h.value = 0; }
  if (f.elements['VWTStoreChangesButton']) {
    f.elements['VWTStoreChangesButton'].value = 'Store quantities';
    f.submit();
    return true;
  }
  return void(0);
}

function continueLMShopping() {
  window.location.href = "/index.php/LM/Order-Publications";
}

function lmViewCart() {
  var f = document.forms['lmcheckoutform'];
  if (!f) { return false; }
  if (f.elements['lmbasketcount'] && f.elements['lmbasketcount'].value) {
    window.location.href = "/index.php/shop/basket/";
  } else {
    alert("There are no items in your cart");
  }
}

function lmCheckOut() {
  var f = document.forms['lmcheckoutform'];
  if (!f) { return false; }
  if (f.elements['lmbasketcount'] && f.elements['lmbasketcount'].value) {
    f.submit();
  } else {
    alert("There are no items in your cart");
  }
}

function lmStore() {
  var f = document.forms['lmaddrform'];
  if (!f) { return false; }
  if (validateRegistration(f)) {
    f.submit();
  }
  return void(0);
}


function lmResourceReq() {
  var f = document.forms['lmaddrform'];
  if (!f) { return false; }
  if (validateRequest(f)) {
    f.submit();
  }
  void(0);
}

function lmPayment() {
  var f = document.forms['lmaddrform'];
  if (checkTermsAndConditions(f)) {
    f.submit();
  }
}

function checkTermsAndConditions(f) {
  var a = f.elements['lmconfirm'];
  if (!a || !a.length) { return false; }
  var checked = false;
  for (var i = 0; i < a.length; i++) {
    if (a[i].checked) {
      if (a[i].value == "agree") { 
        checked = true;
        break; 
      } else {
        if (confirm('By disagreeing with the terms and conditions, you will not be able to proceed with this order. Are you sure you want to cancel this order?')) {
           window.location = "/index.php/LM/Order-Publications";
           return false;
         }
         return false;
      }
    }
  }
  if (!checked) {
    alert("Please indicate whether you agree with these Terms and Conditions");
    return false;
  }
  return true;
}

function storeLMQuantityChange(basketid, val) {
  var f = document.forms['lmbasketform'];
  if (!f) { return void(0); }
  var h = f.elements['lmbaskethidden'+basketid];
  if (!h) { return void(0); }
  h.value = val;
}

function validateRegistration(f) {
  if (checkField(f, 'Salutation', 'Please provide your title') ||
      checkField(f, 'FirstName', 'Please provide your first name') ||
      checkField(f, 'LastName', 'Please provide your last name') ||
      checkField(f, 'EMail', 'Please provide your email address') ||
      checkEmail(f, 'EMail', 'Please provide a valid email address') ||
      checkField(f, 'Address1', 'Please provide the first line of your address') ||
      checkField(f, 'Town', 'Please provide your city') ||
      checkField(f, 'Zip', 'Please provide your postal or zip code') ||
      checkField(f, 'Country', 'Please provide your country') 
      ) {
    return false;
  }
  var country = f.elements['Country'].options[f.elements['Country'].selectedIndex].value;
  if ((country == "US" || country == "CA") && 
      checkField(f, 'State', 'Please provide your state or province')) {
      return false;
  }
  return true;
}

function validateRequest(f) {
  if (checkField(f, 'Salutation', 'Please provide your title') ||
      checkField(f, 'FirstName', 'Please provide your first name') ||
      checkField(f, 'LastName', 'Please provide your last name') ||
      checkField(f, 'EMail', 'Please provide your email address') ||
      checkEmail(f, 'EMail', 'Please provide a valid email address') ||
      checkField(f, 'Address1', 'Please provide the first line of your address') ||
      checkField(f, 'Town', 'Please provide your city') ||
      checkField(f, 'Zip', 'Please provide your postal or zip code') ||
      checkField(f, 'Country', 'Please provide your country') ||
      checkField(f, 'ResTitle', 'Please provide the title of the resource you are requesting') ||
      checkField(f, 'NumCopies', 'Please provide the number of copies you are requesting') ||
      checkField(f, 'Reason', 'Please provide the the reason for this request')
      ) {
    return false;
  }
  if (document.getElementById) {
    var num = document.getElementById("NumCopies");
    if (isNaN(num.value) || num.value < 0) {
      alert("Please provide the number of copies you are requesting");
      num.select();
      num.focus();
      return false;
    }
  }
  return true;
}

// Canada Post Ajax Javascript to return shipping costs

var caPostAjaxReq = null;
var caPostTimeout = null;

function updateShipping(f) {
    if (!f.elements['Zip'].value || f.elements['Country'].selectedIndex < 1) {
        return void(0);
    }
    getCAPostShippingCost(f.elements['Zip'].value,
                          f.elements['Country'].options[f.elements['Country'].selectedIndex].value,
                          f.elements['State'].options[f.elements['State'].selectedIndex].value,
                          f.elements['Town'].value);
}

function getCAPostShippingCost(zip, country, state, city) {
    if (!zip || !country) {
        return false;
    }

    var url = "/index.php/capostshipping/lookup?zip=" + escape(zip) + "&country=" + escape(country) +
           "&state=" + escape(state) + "&city=" + escape(city);
    url_list = url.split('+');
    url = url_list.join('%2B', url);
    if (caPostAjaxReq && caPostAjaxReq.readyState == 1) {
        caPostAjaxReq.abort();
    }
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        caPostAjaxReq = new XMLHttpRequest();
        if (caPostAjaxReq.overrideMimeType) {
            caPostAjaxReq.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            caPostAjaxReq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                caPostAjaxReq = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!caPostAjaxReq) {
         alert('Giving up - Cannot create an shipping request. Your browser may not support this feature.');
        return false;
    }
    if (document.getElementById) {
        var shippingcost = document.getElementById('shippingcost');
        shippingcost.innerHTML = "Updating shipping cost. Please wait...";
        var fullcost = document.getElementById('fullcost');
        var f = document.forms['lmaddrform'];
        var basecost = 0.00;
        if (f && f.elements['basecost']) {
            basecost = parseFloat(f.elements['basecost'].value);
            fullcost.innerHTML = "CAD $ " + basecost.toFixed(2);
        }
    }
    caPostAjaxReq.onreadystatechange = updateCAPostShipping;
    caPostAjaxReq.open('GET', url, true);
    if (caPostAjaxReq) { caPostAjaxReq.send(null); }
}

function updateCAPostShipping() {
      var shippingcost = document.getElementById('shippingcost');
      if (caPostAjaxReq) {
          if (caPostAjaxReq.readyState == 4 &&
              caPostAjaxReq.status == 200) {

              var xmldoc = caPostAjaxReq.responseXML;
              var error = xmldoc.getElementsByTagName('error').item(0);
              var fullcost = document.getElementById('fullcost');
              var f = document.forms['lmaddrform'];
              var basecost = 0.00;
              if (f && f.elements['basecost']) {
                  basecost = parseFloat(f.elements['basecost'].value);
              }
              if (error && error.firstChild && error.firstChild.data) {
                  var msg = xmldoc.getElementsByTagName('message').item(0);
                  shippingcost.innerHTML = msg.firstChild.data;
                  fullcost.innerHTML = "CAD $ " + basecost.toFixed(2);
              } else {
                  var cost = xmldoc.getElementsByTagName('cost').item(0);
                  var prod = xmldoc.getElementsByTagName('product').item(0);
                  shipping = parseFloat(cost.firstChild.data);
                  shippingcost.innerHTML = "$ " + shipping.toFixed(2) + " (" + prod.firstChild.data + ")";
                  var newcost = parseFloat(cost.firstChild.data) + basecost;
                  fullcost.innerHTML = "CAD $ " + newcost.toFixed(2);
              }
              caPostAjaxReq = false;
          }
      }
}

function manualShippingUpdate() {
  var f = document.forms['lmaddrform'];
  if (!f) { return void(0); }
  if (checkField(f, 'Town', 'Please provide your city') ||
      checkField(f, 'Zip', 'Please provide your postal/zip code') ||
      checkField(f, 'Country', 'Please provide your country')) {
    return void(0);
  }
  var c = f.elements['Country'].options[f.elements['Country'].selectedIndex].value;
  if ((c == "US" || c == "CA") &&
      f.elements['State'].selectedIndex <= 0) {
    alert("Please provide your State/Province");
    return void(0);
  }
  updateShipping(f);
}

function countryRightSideSelected(year, type){
	var location = "/" + type + "/" + year + "/";
	switch(year){
		case '2009':
			location = location + "countries/"; 
			break;
		default:
			break;
	}
	location = location + $("#avaible_options :selected").val();
	var path = "http://lm.icbl.org/index.php/publications/display?url=" + location.substring(1);
	$('#right_side_dropdowns').attr("action", path);
	$('#right_side_dropdowns').submit();
}
function countryIndexSelected(year, type){
	var location = "/" + type + "/" + year + "/";
	switch(year){
		case '2009':
			location = location + "countries/"; 
			break;
		default:
			break;
	}
	location = location + $("#avaible_options :selected").val();
	var path = "http://lm.icbl.org/index.php/publications/display?url=" + location.substring(1);
	$('#index_dropdowns').attr("action", path);
	$('#index_dropdowns').submit();
}
function tocRightSideSelected(){
	var path = "http://lm.icbl.org/index.php/publications/display?url=" + $('#toc_select :selected').val();
	//alert($('#right_side_toc').attr("action"));
	$('#right_side_toc').attr("action", path);
	$('#right_side_toc').submit();
}
function validatePQS(){
	//alert($('#pqs_year :selected').val());
	if( ($('#pqs_year :selected').val() == '') && ($('#pqs_type :selected').val() == '') ){ 
		alert("Please enter a year and report type before submitting.");
		return false;
	}
	else if($('#pqs_year :selected').val() == ''){ 
		alert("Please enter a year before submitting.");
		return false; 
	}
	else if($('#pqs_type :selected').val() == ''){ 
		alert("Please enter a report type before submitting.");
		return false;
	}
	
	// Determine if one of the selected options has a 'rel' attribute.
	// The rel attribute can be used to specify a location for the
	// publication (rather than use the form submission).
	var rel = null;
	if(!rel) rel = $('#pqs_section :selected').attr('rel');
	if(!rel) rel = $('#pqs_report :selected').attr('rel');
	if(!rel) rel = $('#pqs_type :selected').attr('rel');
	
	if(rel) {
		// Redirect to the location specified by the 'rel' attribute.
		document.location = rel;
	} else {
		// Submit the form
		$('#pqs_form').submit();
	}
}
function jumpToSubsection(){
	window.location = $('#right_side_sections #pqs_report').val();
}
