var loading = false;
var table_reload = false;
var bom_reload = false;
var target = 1;
var demo_mode = false;
//live
//var config_location = "/configurator/rmcConfigurator/";
//var asset_location = "/assets/";

//test
var config_location = "configurator/rmcConfigurator/";
var asset_location = "assets/";

function rmcSetToDemo() {
	config_location = "/configurator/rmcConfiguratorDemo/";	
	demo_mode = true;
}

function rmcAddInputSubmitEvent(form, input) {
    input.onkeydown = function(e) {
        e = e || window.event;
        if (e.keyCode == 13) {
            //rmcNext(); // for now, want it to do nothing
            return false;
        }
    };
}

function rmcUnsetEnter() {
    var forms = document.getElementsByTagName('form');

    for (var i=0;i < forms.length;i++) {
        var inputs = forms[i].getElementsByTagName('input');

        for (var j=0;j < inputs.length;j++)
            rmcAddInputSubmitEvent(forms[i], inputs[j]);
    }
};

window.onload = rmcUnsetEnter();

function rmcAttachEnterKey() {
    var current = rmcFindCurrForm();
    var forms = document.getElementById('rmcForm_' + current);
    var inputs = forms.getElementsByTagName('input');

    for (var j=0;j < inputs.length;j++) {
        rmcAddInputSubmitEvent(forms, inputs[j]);
    }
}


function rmcNext() {
  var current = rmcFindCurrForm();
  rmcTriggerLoadForm(current+1);
}

function rmcBack() {
  var current = rmcFindCurrForm();
  rmcTriggerLoadForm(current-1);
}

function rmcShowCsv() {
    var parameters = rmcConstructParams();
    window.open(config_location + "rmcBomCsv.php?"+parameters);
}

function rmcPrint() {
    var parameters = rmcConstructParams();
    window.open(config_location + "rmcBomPrint.php?"+parameters);
}

function rmcFindCurrForm() {
  for(var i=1; i <= 5; i++) {
    if(document.getElementById("rmcForm_" + i).style.display == "block") {
      return i;
    }
  }
  return 1;
}

function rmcReadCookie(nam) {
  var tC = document.cookie.split('; ');
  for (var i = tC.length - 1; i >= 0; i--) {
    var x = tC[i].split('=');
    if (nam == x[0]) return unescape(x[1]);}
      return null;
}

function rmcWriteCookies() {
   var params = rmcConstructParams();
   var expireDate = new Date();
   expireDate.setUTCFullYear(2030);
   
   document.cookie = 'configurator_params='+escape(params)+'; expires='+expireDate.toUTCString();
}

function rmcTriggerLoadForm(to) {
  var from = rmcFindCurrForm();
  if(to < 1 || to > 5 || (to==from) || (loading == true)) {
    return;
  }
  
  if(from == 2) {
  	validateCustomRailLengths();
  }

  if(to == 1) {
    document.getElementById("cfg_btn_back").src = asset_location + "images/btn_back.png";
  }
  else if(to == 5){
    document.getElementById("cfg_btn_next").src = asset_location + "images/btn_next_inactive.png";
  }

  if(from == 1) {
    document.getElementById("cfg_btn_back").src = asset_location + "images/btn_back_active.png";
  }
  else if(from == 5) {
    document.getElementById("cfg_btn_next").src = asset_location + "images/btn_next_active.png";
  }

  target = to;

  //rmcWriteCookies();
  if(to == 1 ) {
    rmcLoadForm(from,to);
  }
  else {
    rmcMakePOSTRequest( config_location + "rmcForm_" + to + ".php",rmcUpdateFormContents);
  }
}

function rmcLoadForm(from,to) {
  document.getElementById("cfg_"+from+"_tab_img").src = asset_location + "images/cfg_" + from +"_off.png";
  document.getElementById("cfg_"+to+"_tab_img").src = asset_location + "images/cfg_" + to +"_on.png";
  document.getElementById("rmcForm_"+from).style.display="none";
  document.getElementById("rmcForm_"+to).style.display="block";


}

function rmcUpdateFormContents() {
  var current = rmcFindCurrForm();

  if (http_request.readyState == 4) {
      if (http_request.status == 200) {
          result = http_request.responseText;
          document.getElementById('rmcForm_'+(target)).innerHTML = result;
          rmcLoadForm(current,target);
      } else {
          alert('There was a problem with the request.');
      }
      loading = false;
  }
}

function rmcMakePOSTRequest(url,callback) {
    if( loading == true ){
        return;
    }
    else{
        loading = true;
    }
    var parameters = rmcConstructParams();
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            http_request.overrideMimeType('text/html');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    if (!http_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }

    http_request.onreadystatechange = function() {
    	callback();
    	rmcUnsetEnter();
    };
    
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", parameters.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(parameters);
}

function rmcConstructParams() {
  var params = new Array();
  for(var i = 1; i <= 5; i++) {
    var formElements = document.getElementById("rmcForm_" + i).elements;
    for(var j = 0; j < formElements.length; j++) {
      if(formElements[j].type == 'checkbox' || formElements[j].type == 'radio') {
        if(formElements[j].checked) {
          params.push(formElements[j].name + "=" + encodeURIComponent(formElements[j].value));
        }
      }
      else {
        params.push(formElements[j].name + "=" + encodeURIComponent(formElements[j].value));
      }
    }
  }
  return params.join("&");
}

function rmcAddRow() {
  var rowsCreated = parseInt(document.getElementById("rmcRowsCreated").value) + 1;
  var new_row = document.createElement("div");
  new_row.setAttribute("class","cfg_form_row left");
  new_row.innerHTML = "    <div class=\"cfg_form_block left\"><input type=\"text\" style=\"width: 50px\" name=\"numModsInRow[]\" value=\"0\" onchange=\"rmcUpdateTableTrigger()\"></div>\n"+
    "    <div class=\"cfg_form_block left\"><input type=\"text\" style=\"width: 50px\" name=\"quantityRows[]\" value=\"1\" onchange=\"rmcUpdateTableTrigger()\"></div>\n"+
    "    <div class=\"cfg_form_block left\"><input type=\"radio\" class=\"orientation\" name=\"modOrientation[" + rowsCreated +"]\" value=\"portrait\" checked=\"checked\" onchange=\"updateTiltLegLength()\"> Profile</div>\n"+
    "    <div class=\"cfg_form_block left\"><input type=\"radio\" class=\"orientation\"  name=\"modOrientation[" + rowsCreated +"]\" value=\"landscape\" onchange=\"updateTiltLegLength()\"> Landscape</div>\n"+
    "    <div class=\"cfg_row_delete left\"><img src=\"" + asset_location + "images/icon_delete.png\" onclick=\"rmcRemoveRow(this)\"></div>\n";

  document.getElementById("rmcModulesPerRowArea").appendChild(new_row);
  document.getElementById("rmcRowsCreated").value = rowsCreated;
  rmcUpdateTableTrigger();
}

function rmcRemoveRow(element) {
  var rem_node = element.parentNode.parentNode;
  var parent = rem_node.parentNode;
  parent.removeChild(rem_node);
  var height = document.getElementById("table1MainBorderBody").style.height;
  height = parseInt(height.substr(0,height.length -2));
  height -= 35;
  if(height < 130) {
  	height = 130;
  }
  document.getElementById("table1MainBorderBody").style.height = height+"px";
  rmcUpdateTableTrigger();
}

function rmcUpdateTableTrigger() {
  if(loading) {
    table_reload = true;
  }
  else {
    rmcMakePOSTRequest(config_location + "rmcForm1Table.php",rmcUpdateTable);
  }
}

function rmcUpdateTable() {
  if (http_request.readyState == 4) {
      if (http_request.status == 200) {
          result = http_request.responseText;
          document.getElementById("rmcForm1TableWrapper").innerHTML = result;
          updateTiltLegLength();
      } else {
          alert('There was a problem with the request.');
      }
      loading = false;
      if(table_reload) {
        table_reload = false;
        rmcUpdateTableTrigger();
      }
  }


}

function rmcUpdateDiscountTrigger() {
  if(loading) {
    bom_reload = true;
  }
  else {
    rmcMakePOSTRequest(config_location + "rmcBomHtml.php",rmcUpdateDiscount);
  }
}

function rmcUpdateDiscount() {
  if (http_request.readyState == 4) {
      if (http_request.status == 200) {
          result = http_request.responseText;
          document.getElementById("rmcForm5BomArea").innerHTML = result;
      } else {
          alert('There was a problem with the request.');
      }
      loading = false;
      if(bom_reload) {
        bom_reload = false;
        rmcUpdateDiscountTrigger();
      }
  }


}

function updateModuleModelsTrigger() {
  rmcMakePOSTRequest(config_location + "rmcForm1ModuleModels.php",updateModuleModels);
}

function updateModuleModels() {
  if (http_request.readyState == 4) {
      if (http_request.status == 200) {
          //alert(http_request.responseText);
          result = http_request.responseText;
          document.getElementById("rmcModModelWrapper").innerHTML = result;
      } else {
          alert('There was a problem with the request.');
      }
      loading = false;
  }


}

function updateTiltLegLength() {
  var hasLand = false;
  var hasPort = false;
  var orientationSet = $(".orientation:checked");
  
  for(var i = 0; i < orientationSet.length; i++) {
    if(orientationSet[i].value == 'portrait') {
      hasPort = true;
    }
    else {
      hasLand = true;
    }
  }

  var landlength = $("#rmcModulePortraitWidth").val();
  var portlength = $("#rmcModuleLandscapeWidth").val();
  var length = 0;
  var type = 'f';
  
  if($("#rmcTiltLeg option:selected")) {
    formValue = $("#rmcTiltLeg option:selected").val();
    length = parseInt(formValue);
    type = formValue.substr(formValue.length-1);
  }
  
  var landtilt_min = 0;
  var landtilt_max = 0;
  var porttilt_min = 0;
  var porttilt_max = 0;
  
  if(length > 0) {
    if(type == 'a') {

      landtilt_min = Math.round( Math.atan((length+2)/landlength)*180/Math.PI );
      landtilt_max = Math.round( Math.atan((length*2-10)/(landlength*0.7))*180/Math.PI );
      porttilt_min = Math.round( Math.atan((length+2)/portlength)*180/Math.PI );
      porttilt_max = Math.round( Math.atan((length*2-10)/(portlength*0.7))*180/Math.PI );
    }
    else {

      landtilt_min = Math.round( Math.atan((length-6)/landlength)*180/Math.PI );;
      landtilt_max = Math.round( Math.atan((length-6)/(landlength*0.7))*180/Math.PI );  
      porttilt_min = Math.round( Math.atan((length-6)/portlength)*180/Math.PI );
      porttilt_max = Math.round( Math.atan((length-6)/(portlength*0.7))*180/Math.PI );
    }
 }
  
 $("#rmcTiltLegLength").val(length);
  
  if(hasPort && hasLand) {
    $("#rmcMinAngle").val( Math.min(landtilt_min,porttilt_min) );
    $("#rmcMaxAngle").val( Math.max(landtilt_max,porttilt_max) );
    $("#rmcMinAngleVisual").html( Math.min(landtilt_min,porttilt_min) );
    $("#rmcMaxAngleVisual").html( Math.max(landtilt_max,porttilt_max) );
  }
  else if(hasPort) {
    $("#rmcMinAngle").val( porttilt_min );
    $("#rmcMaxAngle").val( porttilt_max );
    $("#rmcMinAngleVisual").html( porttilt_min );
    $("#rmcMaxAngleVisual").html( porttilt_max );
  }
  else {
    $("#rmcMinAngle").val( landtilt_min );
    $("#rmcMaxAngle").val( landtilt_max );
    $("#rmcMinAngleVisual").html( landtilt_min );
    $("#rmcMaxAngleVisual").html( landtilt_max );  
  }

  updateFootingAndStandoffs( );
  updateTiltAngle( );
}

function updateFootingAndStandoffs( ) {
  var maxTilt = $("#rmcMaxAngle").val();

  var footingLabel = "Adjustable L-Feet";
  var footing = "adjustlfeet";

  if(maxTilt > 0) {
    footingLabel = "Tilt Leg Bracket Kit";
    footing = "tiltlegkit"

    var options = document.getElementById("rmcStandOffs").options;
    if(document.getElementById("rmcFootingType").value != footing) {
    	for(i = 0; i< 4; i++) {
    		options[i].disabled = true;
    	}
     	for(i = 4; i< options.length; i++) {
    		options[i].disabled = false;
    	}
    	options[4].selected = true;
    }


  }
  else {
    var options = document.getElementById("rmcStandOffs").options;
    if(document.getElementById("rmcFootingType").value != footing) {
    	for(i = 0; i< 4; i++) {
    		options[i].disabled = false;
    	}
     	for(i = 4; i< options.length; i++) {
    		options[i].disabled = true;
    	}
    	options[0].selected = true;
    }

  }
  document.getElementById("rmcFootingType").value = footing;
}

function updateTiltAngle( ) {

  lastValue =  $("#rmcTiltAngle option:selected").val();
  tiltSelect = $("#rmcTiltAngle").empty();
  
  minAngle =  $("#rmcMinAngle").val();
  maxAngle =  $("#rmcMaxAngle").val();

  for(i = 0; i < 45; i+=5) {
    if(i > maxAngle)
      break;
    if(i < minAngle)
      continue;
      
    optionHtml = "<option value='"+i+"' ";
    if(i == lastValue)
      optionHtml += "selected";
    
    optionHtml += ">" + i + " degree(s)</option>";
    
    tiltSelect.append(optionHtml);
  }
}

function updateTiltLegLengthEngPage( ) { 
  updateTiltLegLength();
  updateEngValuesTrigger();
}

function updateStandOffs() {
  if(document.getElementById("rmcUseStandOffs").checked) {
    document.getElementById("rmcStandOffs").disabled = false;
    document.getElementById("rmcOateyFlashings").disabled = false;
    document.getElementById("rmcQuickMountFlashings").checked = false; 
  }
  else {
    document.getElementById("rmcStandOffs").disabled = true;
    document.getElementById("rmcOateyFlashings").disabled = true;
  }
}

function updateQuickMountFlashing() {
  if(document.getElementById("rmcUseStandOffs").checked) {
    document.getElementById("rmcUseStandOffs").checked = false; 
    updateStandOffs();
  }
}


function updateCustomLengths() {
  if(document.getElementById("rmcRailLengths").value == "custom") {
    if(document.getElementById("rmcRailType").value == "xrs") {
      document.getElementById("rmcCustomXRSLengths").style.display = "block";
      document.getElementById("rmcCustomXRLLengths").style.display = "none";
    }
    else {
      document.getElementById("rmcCustomXRLLengths").style.display = "block";
      document.getElementById("rmcCustomXRSLengths").style.display = "none";
    }
  }
  else {
    document.getElementById("rmcCustomXRLLengths").style.display = "none";
    document.getElementById("rmcCustomXRSLengths").style.display = "none";
  }
}

function updateCustomLengthsDup() {
  document.getElementById("rmcRailLengths").value = document.getElementById("rmcRailLengthsDup").value;
  document.getElementById("rmcRailType").value = document.getElementById("rmcRailTypeDup").value;
  if(document.getElementById("rmcRailLengthsDup").value == "custom") {
    if(document.getElementById("rmcRailTypeDup").value == "xrs") {
      document.getElementById("rmcCustomXRSLengthsDup").style.display = "block";
      document.getElementById("rmcCustomXRLLengthsDup").style.display = "none";
      document.getElementById("rmcCustomXRSLengths").style.display = "block";
      document.getElementById("rmcCustomXRLLengths").style.display = "none";
    }
    else {
      document.getElementById("rmcCustomXRLLengthsDup").style.display = "block";
      document.getElementById("rmcCustomXRSLengthsDup").style.display = "none";
      document.getElementById("rmcCustomXRLLengths").style.display = "block";
      document.getElementById("rmcCustomXRSLengths").style.display = "none";
    }
  }
  else {
    document.getElementById("rmcCustomXRLLengthsDup").style.display = "none";
    document.getElementById("rmcCustomXRSLengthsDup").style.display = "none";
    document.getElementById("rmcCustomXRLLengths").style.display = "none";
    document.getElementById("rmcCustomXRSLengths").style.display = "none";
  }
  updateEngValuesTrigger();
}

function updateAttachSpacing() {
  rmcUpdateTableTrigger();
}

function runLayoutFormUpdates() {
//  rmcReadCookie('');
    var tooltips=[]
    tooltips[0]="The IronRidge roof mount rails come in two different style:<br>" +
        "&nbsp&nbsp(1)  The popular and best performing XRS (Standard rail)<br>" +
        "&nbsp&nbsp(2)  The cost-effective XRL (Light rail)<br>" +
        "<br>" +
        "The XRS rail can support spans over 12 feet long depending on project conditions.<br>" +
        "The XRL rail can support spans over 8 feet long depending on project conditions";
        
    rmcCreateTip("Options",tooltips);
}

function runOptionsFormUpdates() {
    rmcAttachEnterKey();
    //updateTiltLegLength(); //moved up a tab so not needed
    updateFootingAndStandoffs( );
    updateStandOffs();
    updateCustomRailLengthsLoading();
   
//    updateCustomLengths();
}

function runEngFormUpdates() {
  rmcAttachEnterKey();
//  updateCustomLengthsDup();
}

function mirrorSelection(current,length) {
  if (document.getElementById("rmcCustomXRLLength" + length) != null) {
    document.getElementById("rmcCustomXRLLength" + length).checked = current.checked;
  }
  if (document.getElementById("rmcCustomXRSLength" + length) != null) {
    document.getElementById("rmcCustomXRSLength" + length).checked = current.checked;
  }
  if (document.getElementById("rmcCustomXRLLengthDup" + length) != null) {
    document.getElementById("rmcCustomXRLLengthDup" + length).checked = current.checked;
  }
  if (document.getElementById("rmcCustomXRSLengthDup" + length) != null) {
    document.getElementById("rmcCustomXRSLengthDup" + length).checked = current.checked;
  }
}

function updateEngValuesTrigger() {
  rmcWriteCookies();
  rmcMakePOSTRequest(config_location + "rmcEngForms.php",updateEngValues);
}

function updateEngValues() {
  if (http_request.readyState == 4) {
      if (http_request.status == 200) {
          //alert(http_request.responseText);
          result = http_request.responseText;
          document.getElementById("rmcForm3ContentArea").innerHTML = result;
      } else {
          alert('There was a problem with the request.');
      }
      loading = false;
  }
}

function validateForm4() {
  var orig_phone = document.getElementById("rmcPhone").value;
  var new_phone = '';
  for(var i = 0; i < orig_phone.length; i++) {
        var c = orig_phone.charAt(i);
        if (((c >= "0") && (c <= "9"))) {
          new_phone += c;
        }
  }
  document.getElementById("rmcPhone").value = new_phone;

  if (document.getElementById("rmcProjectName").value.length > 255) {
    alert("Project Name field is too long (max. 255 characters)");
    return false;
  }
  if (document.getElementById("rmcContactName").value.length > 255) {
    alert("Contact Name field is too long (max. 255 characters)");
    return false;
  }
  if (document.getElementById("rmcAddress").value.length > 500) {
    alert("Project Name field is too long (max. 500 characters)");
    return false;
  }
  if (document.getElementById("rmcCompany").value.length > 255) {
    alert("Company field is too long (max. 255 characters)");
    return false;
  }
  if (document.getElementById("rmcCity").value.length > 255) {
    alert("City field is too long (max. 255 characters)");
    return false;
  }
  if (document.getElementById("rmcStateProvince").value.length > 255) {
    alert("State/Province field is too long (max. 255 characters)");
    return false;
  }
  if (document.getElementById("rmcCountry").value.length > 255) {
    alert("Country field is too long (max. 255 characters)");
    return false;
  }
  if (document.getElementById("rmcZipPostalCode").value.length > 10) {
    alert("Zip/Postal Code field is too long (max. 10 characters)");
    return false;
  }

  if (new_phone.length > 15) {
    alert("Phone field is too long (max. 15 characters)");
    return false;
  }

  if(!email_validate(document.getElementById("rmcEmail").value)) {
    alert("Email field is invalid");
    return false;
  }

  return true;
}

function email_validate(email) {
    var at="@"
    var dot="."
    var lat=email.indexOf(at)
    var lstr=email.length
    var ldot=email.indexOf(dot)
    if(lstr == 0) {
      return true;
    }

    if (email.indexOf(at)==-1){
       return false
    }

    if (email.indexOf(at)==-1 || email.indexOf(at)==0 || email.indexOf(at)==lstr){
       return false
    }

    if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 || email.indexOf(dot)==lstr){
        return false
    }

     if (email.indexOf(at,(lat+1))!=-1){
        return false
     }

     if (email.substring(lat-1,lat)==dot || email.substring(lat+1,lat+2)==dot){
        return false
     }

     if (email.indexOf(dot,(lat+2))==-1){
        return false
     }

     if (email.indexOf(" ")!=-1){
        return false
     }

     return true;
}

function validateCustomRailLengths() {
	if(document.getElementById("rmcRailLengthsCst").checked) {
		var checkedRails = document.getElementsByName("customRailLengths[]");
		for(i = 0; i < checkedRails.length; i++) {
			if(checkedRails[i].checked) {
				return true;
			}
		}
		//alert("At least one rail length must be selected before continuing");
		document.getElementById("rmcRailLengthsStd").checked = true;
		return false;
	}
	
	return true;
}

function updateCustomRailLengthsLoading() {
	if(document.getElementById("rmcRailLengthsCst").checked) {
		document.getElementById("rmcCustomLengthsBox").style.display = "block";
	}
	else {
		document.getElementById("rmcCustomLengthsBox").style.display = "none";
	}
	
}

function updateCustomRailLengths() {
	if(document.getElementById("rmcRailLengthsCst").checked) {
		document.getElementById("rmcCustomLengthsBox").style.display = "block";
	}
	else {
		document.getElementById("rmcCustomLengthsBox").style.display = "none";
	}
	
	if(!document.getElementById("rmcRailLengthsStd").checked && 
		document.getElementById("rmcSystemWatts").value < 100000) {
		//alert("All rail lengths may not be available except for projects over 100kW");
	}

}

function rmcCreateTip(page,tooltips){
    for(var i = 0; i < tooltips.length; i++) {
    	if ($('#rmc' +page + i).length==0){
		$('<div id="rmc' +page + i + '" class="rmctooltip" />').html(tooltips[0] + '</div>')
				.appendTo(document.body)
	}
    }
}

function rmcPositionTooltip($tooltip,e){
	var tooltipoffsets = [20,-30];
	var x=e.pageX+tooltipoffsets[0];
	var y=e.pageY+tooltipoffsets[1];
	var tipw=$tooltip.outerWidth();
	var tiph=$tooltip.outerHeight();
	x=(x+tipw>$(document).scrollLeft()+$(window).width())? x-tipw-(tooltipoffsets[0]*2) : x;
	y=(y+tiph>$(document).scrollTop()+$(window).height())? $(document).scrollTop()+$(window).height()-tiph-10 : y;
	$tooltip.css({left:x, top:y})
}

function rmcMoveBox(tipid,e) {
	var $tooltip=$("#rmcOptions0");
	rmcPositionTooltip($tooltip, e);
}

function rmcShowBox(tipid,e) {
	var $tooltip=$("#rmcOptions0");
	$tooltip.show();
	rmcPositionTooltip($tooltip, e);
}

function rmcHideBox(tipid,e) {
	var $tooltip=$("#rmcOptions0");
	$tooltip.hide();
}

