//form validation for search
function submitThis(container) {
  //set address input
  var address = document.getElementById('addr').value;
  var city = document.getElementById('city').value;
  var zip = document.getElementById('zip').value;
  var i_state = document.getElementById('state');
  var state = i_state.options[i_state.selectedIndex].value;
  var i_country = document.getElementById('country');

  //check for input
  if ( (city=="" || state=="") && (zip=="") ) {
    alert('Please enter a city and select a province, or enter a postal code');
    return false;
  }
  
  var zipType = 0;
  if(zip.length > 0){
	var fcZip = zip.charAt(0).toLowerCase();
	if ( (fcZip >= '0') && (fcZip <= '9') ){
		zipType = 1;
	}
	else if ( (fcZip >= 'a') && (fcZip <= 'z') ){
		zipType = 2;
	}
	else {
		alert("Please enter a valid Postal/ZIP Code");
		return false;
	}
  }

  //set country code
	if(state != ""){
	  if ( state=="AB" || state=="BC" || state=="MV" || state=="MB" || state=="NB" || state=="NL" || state=="NS" || state=="NT" || state=="ON" || state=="PE" || state=="QC" || state=="SK" || state=="YT" ) {
		if(zipType == 0 || zipType == 2){
			i_country.value = "CA";
		}
		else {
			alert("Please enter a Canadian Postal/ZIP Code");
			return false;
		}
	  } 
	  else {
		if(zipType == 0 || zipType == 1){
			i_country.value = "US";
		}
		else {
			alert("Please enter a US Zip Postal/ZIP Code");
			return false;
		}
	  }
	}
	else {
		if(zipType == 2){
			i_country.value = "CA";
		}
		else if(zipType == 1){
			i_country.value = "US";
		}
	}
  setSearchRadius();
}


//form validation for Trip Planner
function submitTripPlanner(container) {
  //set address input
  var oaddress = document.getElementById('origaddr').value;
  var ocity = document.getElementById('origcity').value;
  var ozip = document.getElementById('origzip').value;
  var oi_state = document.getElementById('origstate');
  var ostate = oi_state.options[oi_state.selectedIndex].value;
  var oi_country = document.getElementById('origcountry');
  
  var daddress = document.getElementById('destaddr').value;
  var dcity = document.getElementById('destcity').value;
  var dzip = document.getElementById('destzip').value;
  var di_state = document.getElementById('deststate');
  var dstate = di_state.options[di_state.selectedIndex].value;
  var di_country = document.getElementById('destcountry');

  //check for input
  if ( (ocity=="" || ostate=="") && (ozip=="") ) {
    alert('Please enter a city and select a province, or enter a postal code for the starting point');
    return false;
  }
  if ( (dcity=="" || dstate=="") && (dzip=="") ) {
    alert('Please enter a city and select a province, or enter a postal code for the destination');
    return false;
  }

  //set country code
  if ( ostate=="AB" || ostate=="BC" || ostate=="MV" || ostate=="MB" || ostate=="NB" || ostate=="NL" || ostate=="NS" || ostate=="NT" || ostate=="ON" || ostate=="PE" || ostate=="QC" || ostate=="SK" || ostate=="YT" ) {
    oi_country.value = "CA";
  } else {
    oi_country.value = "US";
  }
  if ( dstate=="AB" || dstate=="BC" || dstate=="MV" || dstate=="MB" || dstate=="NB" || dstate=="NL" || dstate=="NS" || dstate=="NT" || dstate=="ON" || dstate=="PE" || dstate=="QC" || dstate=="SK" || dstate=="YT" ) {
    di_country.value = "CA";
  } else {
    di_country.value = "US";
  }

  setSearchRadius();
}


function ambSubmit() {
  setSearchRadius();
}

function setSearchRadius() {
  //set the radius distance and units (km or mi)
  //REQUIREMENTS: input tags with IDs "radius" and "units"
  //REQUIREMENTS: ID of radius dropdown must be "searchradius"
  var sr = document.getElementById('searchradius');
  var searchradius = sr.options[sr.selectedIndex].value;
  var radius = document.getElementById('radius');
  var units = document.getElementById('units');
  radius.value = 0; units.value = "";

  switch(searchradius) {
    case('.5km'):
      radius.value = '.5';
      units.value = 'km';
      break;
    case('1km'):
      radius.value = '1';
      units.value = 'km';
      break;
    case('1.5km'):
      radius.value = '1.5';
      units.value = 'km';
      break;
    case('2km'):
      radius.value = '2';
      units.value = 'km';
      break;
    case('5km'):
      radius.value = '5';
      units.value = 'km';
      break;
    case('10km'):
      radius.value = '10';
      units.value = 'km';
      break;

    case('.5mi'):
      radius.value = '.5';
      units.value = 'mi';
      break;
    case('1mi'):
      radius.value = '1';
      units.value = 'mi';
      break;
    case('1.5mi'):
      radius.value = '1.5';
      units.value = 'mi';
      break;
    case('2mi'):
      radius.value = '2';
      units.value = 'mi';
      break;
    case('3mi'):
      radius.value = '3';
      units.value = 'mi';
      break;
    case('10mi'):
      radius.value = '10';
      units.value = 'mi';
      break;
    case('50mi'):
      radius.value = '50';
      units.value = 'mi';
      break;

    default :
      radius.value = '.5';
      units.value = 'km';
      break;
  }
}

function popCopyright() {
  copyURL = 'http://www.mapquest.com/about/copyright2.adp?display=popup';
  newWindow = window.open(copyURL,"copyright","toolbar=no,resizable=no,resize=no,scrollbars=yes,location=no,directories=no,status=no,menubar=no,width=320,height=450");
}

function createLink(container, strURL, caption, className) {
  // abort function if missing container, strURL, or caption
  if(!mq_ParamExists(container) || !mq_ParamExists(strURL) || !mq_ParamExists(caption)) { return; }
  
  var link_div = createDiv(container, '', '');
  var link_href = createA(link_div, strURL, '');

  // use className if available
  if (mq_ParamExists(className) && className.length) {
    link_href.className = className;
  }

  link_href.appendChild(document.createTextNode(caption));
}


function pickRadius(optionContainer, radius, units) {
  //select search radius (latwWidth) for Trip Planner
  if (units == 'mi') {
      if (radius == .5) {
        optionContainer.options[4].selected = true;
      } else if (radius == "1") {
        optionContainer.options[5].selected = true;
      } else if (radius == "1.5") {
        optionContainer.options[6].selected = true;
      } else if (radius == "2") {
        optionContainer.options[7].selected = true;
      } else {
        optionContainer.options[4].selected = true;
    }
  } else {
    if (radius == .5) {
      optionContainer.options[0].selected = true;
    } else if (radius == "1") {
      optionContainer.options[1].selected = true;
    } else if (radius == "1.5") {
      optionContainer.options[2].selected = true;
    } else if (radius == "2") {
      optionContainer.options[3].selected = true;
    } else {
      optionContainer.options[0].selected = true;
    }
  }
}


//creates the url using record ID for a locmap request
function generateIdMap(loc) {
    var url = "advantage.adp?transaction=locmap";
        url+= "&recordid="+ loc.recordId;
        url+= "&pwidth=400&pheight=324";
    return url;
}

//TripPlanner Version of mq_display_address_location
function mq_display_latw_location(container, loc) {
    var bSpace=false;

    if(!mq_ParamExists(loc))
        return;

    var div = createDiv (container, '', '');
    var strURL = generateIdMap(loc);

    var a = createA (div, strURL, '');
    var em = a.appendChild (document.createElement ('b'));
    if (mq_ParamExists(loc.name) && loc.name.length) {
      em.appendChild (document.createTextNode (loc.name));
    } else {
      em.appendChild (document.createTextNode ('Tim Hortons'));
    }
    div.appendChild (document.createElement ('br'));

    if (mq_ParamExists(loc.address) && loc.address.length) {
      div.appendChild (document.createTextNode (loc.address));
      div.appendChild (document.createElement ('br'));
    }
    if (mq_ParamExists(loc.city) && loc.city.length) {
      div.appendChild (document.createTextNode (loc.city + ','));
    }
    if (mq_ParamExists(loc.stateProvince) && loc.stateProvince.length) {
      div.appendChild (document.createTextNode (loc.stateProvince));
      bSpace=true;
    }
    if (mq_ParamExists(loc.postalCode) && loc.postalCode.length) {
      if (bSpace) { div.appendChild (document.createTextNode (' ')); }
      div.appendChild (document.createTextNode (loc.postalCode));
    }
    if (mq_ParamExists(loc.country) && loc.country.length) {
      if(bSpace) { div.appendChild (document.createTextNode (' ')); }
      div.appendChild (document.createTextNode (loc.country));
    }

    if (mq_ParamExists(loc.userFields) && mq_ParamExists(loc.userFields.user4) && loc.userFields.user4.length) {                
      div.appendChild (document.createElement ('br'));
      div.appendChild (document.createTextNode ('Tel: '+ loc.userFields.user4));
    }

    if (mq_ParamExists(loc.distance) && mq_ParamExists(loc.distance.value) && loc.distance.value.length) {
       div.appendChild (document.createElement ('br'));
       div.appendChild (document.createTextNode (loc.distance.value +' '+ loc.distance.units +' from route'));
    }
    div.appendChild (document.createElement ('br'));

    var lAddr = strEncoder(loc.address);
    var lCity = strEncoder(loc.city);

    ddURL = "?transaction=route&template=route_query&destrecordId="+ loc.recordId +"&destphone="+ loc.userFields.user1;
    ddURL += "&destaddress="+ lAddr +"&destcity="+ lCity +"&deststateProvince="+ loc.stateProvince +"&destpostalCode="+ loc.postalCode +"&destcountry="+ loc.country;
    if (av.parameters.units == 'km') { ddURL += "&units=km"; } else { ddURL += "&units=mi"; }
    ddURL += "&pwidth=420&pheight=342";

    var d = createA (div, ddURL, '');
    d.appendChild (document.createTextNode ('Driving Directions'));
    div.appendChild (document.createElement ('br'));
    div.appendChild (document.createElement ('br'));
}

//Replace spaces with plus signs
function strEncoder(s) {
  var b = s.split(" ").join("+");
      b = b.split("&").join("%26");
      b = b.split("é").join("e");
  return b;
}

//zoom buttons on latw
function zoomColor(n, onoff) {
  var container = document.getElementById('latwzoom'+ n);
  
  if (onoff) {
    container.style.backgroundColor = '#817964';
  } else {
    container.style.backgroundColor = '#571C00';
  }
}

//displays the maneuvers table results page for LATW
//this was necessary as their specs for route and latw were very different
function mq_display_latw_maneuvers_table(container, maneuvers, temp) {
    var colorCount = 1;

    //display table header
    var mTable = document.createElement ('table');
        mTable.id = 'mqManList';
        mTable.cellPadding = '0';
        mTable.cellSpacing = '0';
        mTable.border = '0';
        mTable.summary = 'Direction Maneuvers';

    var tbody = document.createElement ('tbody');

    //display the start address line
        var tr1 = document.createElement ('tr');
            var td1 = document.createElement ('td');
                td1.className = 'gap';
                td1.colSpan = 3;
        if (temp == 'print') {
            mq_display_address_location_single_line(td1, av.origin.getAt[0], '', '', '', 'FROM');
        } else {
            mq_display_address_location_single_line(td1, av.origin.getAt[0], "/images/general/start.gif", '37', '11');
        }
        tr1.appendChild (td1);
        tbody.appendChild (tr1);

    //check if there is a prequel string that needs to be displayed
    if (mq_ParamExists(maneuvers.prequel))   {
        var tr2 = document.createElement ('tr');
            var td2 = document.createElement ('td');
                td2.className = 'gap';
                td2.colSpan = '3';
                createImg (td2, '/images/general/icon_warning_small.gif', '17', '17', '', '', 'warning');
                td2.appendChild (document.createTextNode (maneuvers.prequel));

        tr2.appendChild (td2);
        tbody.appendChild (tr2);
    }

    //output the actual maneuvers alternating colors of the background

    for (var count=0; count < eval(maneuvers.count); count++) {
        var maneuver = maneuvers.getAt[count];

        var tr = document.createElement ('tr');
            tr.className = mq_rowColor(colorCount);

            var tdn = document.createElement ('td');
                tdn.width = '5%';
                tdn.className = 'manLatwNum';
                tdn.appendChild (document.createTextNode (maneuver.number));

            var tdt = document.createElement ('td');
                tdt.width = '32%';
                tdt.className = 'manLatwThumb';
                createImg (tdt, maneuver.thumbnailMap.request, maneuver.thumbnailMap.width, maneuver.thumbnailMap.height, '', '', '');

            var tdm = document.createElement ('td');
                tdm.width = '63%';
                tdm.className = 'manText';
                tdm.appendChild (document.createTextNode (maneuver.text));
                var tdmdiv = createDiv(tdm, 'latwDist', '');
                    if ( maneuver.time > 60 ) {
                      var timeValue = maneuver.time / 60;
                      var timeUnit = 'minutes';
                    } else {
                      var timeValue = maneuver.time;
                      var timeUnit = 'seconds';
                    }
                    
                    tdmdiv.appendChild (document.createTextNode ('Time: '+ timeValue + ' ' + timeUnit));
                    tdmdiv.appendChild (document.createElement ('br'));
                    tdmdiv.appendChild (document.createTextNode ('Distance: '+ maneuver.distance.value + (maneuver.distance.units == "mi" ? " miles" : " kilometres")));

        if(mq_ParamExists(maneuver.searchResults) && eval(maneuver.searchResults.count) > 0) {
            for (var locCount=0; locCount < eval(maneuver.searchResults.count); locCount++)  {
                var loc = maneuver.searchResults.getAt[locCount];

                var div = createDiv (tdm, 'latwPois', '');
                    if (mq_ParamExists (av.proxIconId)) {
                        createImg (div, '/images/icons/' + av.proxIconId + '_' + loc.number + '.gif', '', '', '', '', loc.number);
                    } else {
                        var nDiv = createDiv (div, '', '');
                        nDiv.appendChild (document.createTextNode (loc.number));
                    }
                    mq_display_latw_location (div, loc);
            }
        }
        tr.appendChild (tdn);
        tr.appendChild (tdt);
        tr.appendChild (tdm);
        tbody.appendChild (tr);

        colorCount++;
    }

    //check if there is a sequel string that needs to be displayed
    if (mq_ParamExists(maneuvers.sequel)) {
        var tr3 = document.createElement ('tr');
            var td3 = document.createElement ('td');
                td3.className = 'gap';
                td3.colSpan = '3';
                createImg (td3, '/images/general/icon_warning_small.gif', '17', '17', '', '', 'warning');
                td3.appendChild (document.createTextNode (maneuvers.sequel));

        tr3.appendChild (td3);
        tbody.appendChild (tr3);
    }

    //display the ending destination
        var tr4 = document.createElement ('tr');
            var td4 = document.createElement ('td');
                td4.className = 'gap';
                td4.colSpan = 3;
        if (temp == "print") {
            mq_display_address_location_single_line(td4, av.destination.getAt[0], '', '', '', 'TO');
        } else {
            mq_display_address_location_single_line(td4, av.destination.getAt[0], "/images/general/end.gif", '37', '11');
        }
        tr4.appendChild (td4);
        tbody.appendChild (tr4);

        mTable.appendChild (tbody);
        container.appendChild (mTable);
}

//open map legend available on livesite
function openLegend () {
  var legendUrl     = "http://www.mapquest.com/maps/legend.adp" ;
  var legendOptions = "resizable=no,directories=no,left=10,top=10,toolbar=no,width=270,height=660,scrollbars=no";
  window.open(legendUrl,"MQ_MapLegend",legendOptions);
}

function setCustomParams(loc) {
  if (loc.mapStyle) {
    document.getElementById('mapStyle').value = loc.mapStyle;
  }
  if (loc.pwidth && loc.pheight) {
    document.getElementById('pwidth').value = loc.pwidth;
    document.getElementById('pheight').value = loc.pheight;
  }
  if (loc.destrecordId) {
    document.getElementById('destrecordId').value = loc.destrecordId;
  }
  if (loc.origrecordId) {
    document.getElementById('origrecordId').value = loc.origrecordId;
  }
  if (loc.routeLanguage) {
    document.getElementById('routeLanguage').value = loc.routeLanguage;
  }
}
