///////////////////////////////////////////////////////////////////////////////
//Global vars
//////////////////////////////////////////////////////////////////////////////


function openWin(url,w,h) {
	window.open(url,'pop','width='+w+',height='+h+',scrollbars=no,toolbars=no');
}
//Returns a value of a drop down
function valueOfDropDown(aDropDown){return aDropDown.options[aDropDown.selectedIndex].value;}
//Returns a text of a drop down
function textOfDropDown(aDropDown){return aDropDown.options[aDropDown.selectedIndex].text;}

function isEmail(string) {
    if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
        return true;
    else
        return false;
}
function isDate (day,month,year) {
// checks if date passed is valid
// will accept dates in following format:
// isDate(dd,mm,ccyy), or
// isDate(dd,mm) - which defaults to the current year, or
// isDate(dd) - which defaults to the current month and year.
// Note, if passed the month must be between 1 and 12, and the
// year in ccyy format.
    var today = new Date();
    year = ((!year) ? y2k(today.getYear()):year);
    month = ((!month) ? today.getMonth():month-1);
    if (!day) return false
    var test = new Date(year,month,day);
    if ( (y2k(test.getYear()) == year) &&
         (month == test.getMonth()) &&
         (day == test.getDate()) )
        return true;
    else
        return false
} 

function getOBJ(name,document){return document.getElementById(name);}
function showOBJ(name) {
  theDiv = document.getElementById(''+name);
  theDiv.style.display='block';
}
function hideOBJ(name) {
  theDiv = document.getElementById(''+name);
  theDiv.style.display='none';
}
function popOBJ(name,content) {
  theDiv = document.getElementById(''+name);
  theContent = parent.frames.loader.document.getElementById(''+content).innerHTML;
  theDiv.innerHTML = theContent;
  parent.frames.loader.document.getElementById(''+content).innerHTML = '';
  loading(0);
}
function popOBJWithString(name,content) {
  theDiv = document.getElementById(''+name);
  theDiv.innerHTML = content;
}
function popField(name,myValue) {
  theField = document.getElementById(''+name);
  theValue = myValue;
  //if (theField.value == '') {
    theField.value = myValue;
  //}
  //else {
   // theField.value = theField.value+','+myValue;
  //}
  //alert(theField.value);
}
function setLoaderSrc(iframe, src) {
  loading(1);
  frame = document.getElementById(iframe+'');
  frame.src = src;
}

var hex=255;
function fadeIt(obj, page) {
  buttocks = obj;
  whereTo = page;
  theObj = obj.id;
  theID = theObj;
  startPos = (theID.indexOf('w')+1);
  endPos = theID.length;
  theID = theID.substring( startPos, endPos );

  hex-=11; // increase colour darkness
  obj.style.backgroundColor="rgb("+hex+","+hex+","+hex+")";
  if (hex == 46) {
    hex = 255;
    if (theID.indexOf('&') >= 0 ) {
      startPos = (theObj.indexOf('w')+1);
      endPos = theObj.indexOf('&');
      theID = theObj.substring( startPos, endPos );
      startPos = (theObj.indexOf('&'));
      endPos = theObj.length;
      extras = theObj.substring( startPos, endPos );
      if(whereTo == 'clientDetail.asp') {
        parent.pullTheWool();
      }
      obj.style.backgroundColor="rgb(255,255,255)";
     parent.frames.document.getElementById('contentLoader').src = whereTo+'?recordID='+theID+extras;
    } 
    else {
      if(whereTo == 'clientDetail.asp') {
        parent.pullTheWool();
      }
      obj.style.backgroundColor="rgb(255,255,255)";parent.frames.document.getElementById('contentLoader').src = whereTo+'?recordID='+theID;
    }
  } else {setTimeout("fadeIt(buttocks, whereTo);",20);}
}

function editCell(cell) {
  if (document.all) {
    cell.innerHTML =
    '<input ' +
    ' id="editCell"' +
    ' onclick="event.cancelBubble = true;"' + 
    ' onchange="setCell(this.parentElement, this.value)" ' +
    ' onblur="setCell(this.parentElement, this.value)" ' +
    ' value="' + cell.innerText + '"' +
    ' size="20"' +
    '>';
    document.all.editCell.focus();
    document.all.editCell.select();
  }
  else if (document.getElementById) {
    cell.normalize();
    var input = document.createElement('INPUT');
    input.setAttribute('value', cell.firstChild.nodeValue);
    input.setAttribute('size', cell.firstChild.nodeValue.length);
    input.setAttribute('style', 'font-size:11px;');
    input.onchange = function (evt) { setCell(this.parentNode, this.value); };
    input.onclick = function (evt) { evt.cancelBubble = true; if (evt.stopPropagation) evt.stopPropagation(); };
    cell.replaceChild(input, cell.firstChild);
    input.focus();
    input.select();
  }
}

function setCell(cell, value) {
  if (document.all) {
    cell.innerText = value;
  }
  else if (document.getElementById) {
    cell.replaceChild(document.createTextNode(value), cell.firstChild);
  }
}

function changeClass(obj, newClass, multi) {
  if(multi) {
    for(var i=0;i<mItemCount;i++) {
      theObj = obj+i;
      theObj = getOBJ(theObj,document);
      theObj.className = newClass;
    }
  }
  else {
    theObj = getOBJ(obj,document);
    theObj.className = newClass;
  }
}

function changeImg(img, newImg) {
  img = getOBJ(img,document);
  img.src=newImg;
}

function frameBreak() {
  if (top!= self) top.location=self.document.location; 
}

var vehCount=0;
function orderMeVehicle(vCode, vName, vGrpName, vColour, vQuantity) {
  
  theField = getOBJ('ItemCode',document);
  theColourField = getOBJ('ItemColour',document);
  theGrpNameField = getOBJ('ItemModel',document);
  theNameField = getOBJ('ItemDesc',document);
  theDisplay = getOBJ('depositVehicle',document);
  theCount = getOBJ('vehOrdered',document);
  theQuantityField = getOBJ('ItemQuantity',document);
  //if (vQuantity == 0) {
  //  vQuantity = 1;
    vehCount = vehCount+1;
  //} else { vehCount = parseInt(vehCount)+parseInt(vQuantity); }
  
  //html = '<li>'+vQuantity+' - '+vName+' - '+vColour+' </li>';
  html = '<li>'+vName+' - '+vColour+' </li>';
  for(var i=0;i<vQuantity;i++) {
    if (theField.value == '') {
      theField.value = '\''+vCode+'\'';
      theColourField.value ='\''+vColour+'\'';
      theNameField.value ='\''+vName+'\'';
      theGrpNameField.value ='\''+vGrpName+'\'';
      theQuantityField.value ='\''+vQuantity+'\'';
    }
    else {
      theField.value = theField.value+','+'\''+vCode+'\'';
      theColourField.value = theColourField.value+','+'\''+vColour+'\'';
      theNameField.value = theNameField.value+','+'\''+vName+'\'';
      theGrpNameField.value = theGrpNameField.value+','+'\''+vGrpName+'\'';
      theQuantityField.value = theQuantityField.value+','+'\''+vQuantity+'\'';
    }
  
    if (theDisplay.innerHTML == '') {
      theDisplay.innerHTML = html;
    } else {theDisplay.innerHTML = theDisplay.innerHTML+html;}
  }
//  if (vehCount == 1) {
//    theCount.innerHTML = vehCount+' Vehicle for Order';
//  } else {
    //theCount.innerHTML = vehCount+' Vehicles for Order';//}
    theCount.innerHTML = ' Vehicles for Order'
}

function cancelOrder() {
  theField = getOBJ('ItemCode',document);
  theDisplay = getOBJ('depositVehicle',document);
  theCount = getOBJ('vehOrdered',document);
  theField.value = '';
  theDisplay.innerHTML = '';
  theCount.innerHTML = '';
  vehCount = 0;
}

function emptyInput(input) {
  if(input.value == 'Click to edit') {
    input.value = '';
  }
}

function mailOrder() {
  getOBJ('mailContent',document).value=getOBJ('thisContent',document).innerHTML;
  getOBJ('mailTo',document).value = getOBJ('EmailTo',document).value;
  document.EmailIt.submit();
}

function changeStatus(orderID, type, status) {
  if(type) {
    theField = 'bAppMarketing';
  } else {
    theField = 'bAppFinance';
  }
  setLoaderSrc('loader', 'changeStatus.asp?ipkOrderID='+orderID+'&'+theField+'='+status);
}

function pullTheWool(flip){
  var oListing = document.getElementById('oListing');
  var oDetail = document.getElementById('oDetail');
  if(flip) {
    oListing.style.display = 'none';
    oDetail.style.display = 'block'; 
    oDetail.innerHTML = 'Loading...';
  } else {
    oListing.style.display = 'block';
    oDetail.style.display = 'none';  
  }
}

var row = 0;
function addPart() {
  row++;
  if (row == 10) {
    row = 1;
  }
  var partRow = document.getElementById('partRow'+row);
  if (document.all) {
    partRow.style.display = 'block'; 
  } else {
    partRow.style.display = 'table-row';
  }
  if (row == 9) {
    var addPartBut = document.getElementById('addPartBut');
    addPartBut.style.display = 'none'; 
  }
}

var lRow = 0;
function addLabour() {
  lRow++;
  if (lRow == 10) {
    lRow = 1;
  }
  var labourRow = document.getElementById('labourRow'+lRow);
  if (document.all) {
    labourRow.style.display = 'block'; 
  } else {
    labourRow.style.display = 'table-row';
  }
  if (lRow == 9) {
    var addLabourBut = document.getElementById('addLabourBut');
    addLabourBut.style.display = 'none'; 
  }
}

var crow = 1;
function addComplaint() {
  crow++;
  if (crow == 10) {
    crow = 1;
  }
  var partRow = document.getElementById('complaintRow'+crow);
  if (document.all) {
    partRow.style.display = 'block'; 
  } else {
    partRow.style.display = 'table-row';
  }
  if (crow == 9) {
    var addPartBut = document.getElementById('addComplaintBut');
    addPartBut.style.display = 'none'; 
  }
}

function chooseColour(cell, sName) { 
  var colourSelectStart = 
  '<select name="theColour" class="editable" onchange="gotColour(this.parentElement.id, this.options[this.selectedIndex].text, this.value, \''+sName+'\');">' +
    '<option value="">Select</option>';
  var colourSelectEnd = '</select>';
  var theCell = document.getElementById(cell);
  sName = sName.replace(/--/g, '<option value=\"', '');
  sName = sName.replace(/##/g, '\">');
  sName = sName.replace(/@@/g, '</option>');
  var colourList = sName;
  theCell.innerHTML = colourSelectStart+ colourList +colourSelectEnd;
}

var startColourCell = '<a href="#" onclick="parent.chooseColour(\'';
var middleColourCell = '\');" class="BigLink">';
var endColourCell = '</a>';
function gotColour(cellID, colour, sValue, sName) {
  var theCell = document.getElementById(cellID);
  useCellID = cellID.replace('colour','');
  useCellID = useCellID.replace('floor','');
  var theField = 'vehicles'+useCellID;
  theField = document.getElementById(theField);
  sName = '\''+sName.replace(' ', '');
  theCell.innerHTML = startColourCell + cellID + '\'' + ', ' + sName + middleColourCell + colour + endColourCell;
  theField.value = sValue;
  
}

function loading(status) {
  var showLoading = document.getElementById('showLoading');
  if (status) { showLoading.style.visibility = 'visible'; }
  else { showLoading.style.visibility = 'hidden'; }
}

function serviceType(status) { 
  if (status==0) {
    if (document.all) {
      getOBJ('serviceDealership', document).style.display = 'block';
      getOBJ('theMsg', document).style.display = 'block';
    } else {
      getOBJ('serviceDealership', document).style.display = 'table-row';
      getOBJ('theMsg', document).style.display = 'table-row';
    }
  }
  else {
    getOBJ('serviceDealership', document).style.display = 'none';
    getOBJ('theMsg', document).style.display = 'none';
  }
}

function popServiceType(engNo) {
  theModel = engNo.substring( 6, 8 );
  type = getOBJ('sType', document);
  var tempOption = new Option('PDI', 'PDI');
  type.options[0] = tempOption;
  var j=1;
  
  if (theModel == 'DR') {	  
    for (var i=0;i<=95000;) {
      i=i+5000;
      var tempOption = new Option(i, i);
  		type.options[j] = tempOption;
      j++;
    }
  }
  else {
    var tempOption = new Option(5000, 5000);
    type.options[1] = tempOption;
    j=2;
    for (var i=0;i<=90000;) {
      i=i+10000;
      var tempOption = new Option(i, i);
  		type.options[j] = tempOption;
      j++;
    }
  }
}

function sendPart(serNo, fieldNo) {
  document.location='getpart.asp?serNo='+serNo+'&fieldNo='+fieldNo;
}

function popIt() {
  document.getElementById('SerMenu').style.visibility = 'visible';
  setTimeout("document.getElementById('SerMenu').style.visibility = 'hidden';", 2500);
}

function serviceDiff(kms) {
  if (kms != '') {
    if (isNaN(kms)) { alert('Please enter numbers only in the KMs field'); }
    lastService = document.getElementById('sLastService').value
    diff = parseInt(kms) - parseInt(lastService);
    if (diff > 1500) {
      if(confirm('The service history of this vehicle is not up to date.\nDo you wish to update now?')) {
        setLoaderSrc('loader', 'service.asp');
      }
    }
  }
}

function subLetMe(type,no,checked) {
  if(no != 0) {
    addNo = no;
  }else{
    addNo = '';
  }
  if(type){
    field = document.getElementById('sLReqDesc'+addNo);
    field2 = document.getElementById('sLReqQty'+addNo);
    field3 = document.getElementById('sLReqValue'+addNo);
    field4 = document.getElementById('sLReqRes'+addNo);
  }
  else {
    field = document.getElementById('sPReqPartNo'+addNo);
    field2 = document.getElementById('sPReqDesc'+addNo);
    field3 = document.getElementById('sPReqQty'+addNo);
    field4 = document.getElementById('sPReqValue'+addNo);
  }
  if(checked) {
    field4.readOnly=false;
    field.style.borderColor='#D83132';
    field2.style.borderColor='#D83132';
    field3.style.borderColor='#D83132';
    field4.style.borderColor='#D83132';
  }
  else {
    field4.readOnly=true;
    field.style.borderColor='#C8C8C8';
    field2.style.borderColor='#C8C8C8';
    field3.style.borderColor='#C8C8C8';
    field4.style.borderColor='#C8C8C8';
  }
}

function calcLabour(qty,amount,fieldNo) {
  if(fieldNo != 0) {
    addNo = fieldNo;
  }else{
    addNo = '';
  }
  total = parseInt(qty)*parseInt(amount);
  document.getElementById('sLReqValue'+addNo).value = total;
}

function frmValidation(frmObj) {
  //  Eta my bra. CFML changes the obj. Use '_CF_this' when calling this function instead of 'this' 
  //
  //  Form bits:
  //  <input type="text" param="[boolean],[number_of_validation_script],'[error_message]'">
  //  OR
  //  <input type="text" param="[boolean],'[custom_function_returning_boolean]','[error_message]'">
  //
  //  Ex.
  //  <input type="text" param="1,3,'Please enter your ID number.'">
  //
  with (frmObj) 
  {
    var functionArr = new Array(4);
    var frmObjItem;
	  
    functionArr[0] = 'isEmpty(frmObjItem.value)';
    functionArr[1] = '!isEmail(frmObjItem.value)';
    functionArr[2] = '!isLegal(frmObjItem.value)';
    functionArr[3] = '!isSAID(frmObjItem.value)';

    for (i=0;i<frmObj.length;i++) 
    {
	  	
      if (frmObj[i].attributes['param'] != undefined) 
      {
        tmpArr = frmObj[i].attributes['param'].nodeValue.split(',');
        if (tmpArr[0] == '1') 
        {
          frmObjItem = frmObj[i];
          if (isNaN(tmpArr[1])) 
          {
            if (eval(tmpArr[1].substr(1,tmpArr[1].length-2))) 
            {
              alert(tmpArr[2].substr(1,tmpArr[2].length-2));
              frmObjItem.focus();
              return false;
            }// if
          } 
          else 
          {
            if (eval(functionArr[tmpArr[1]])) 
            {
              alert(tmpArr[2].substr(1,tmpArr[2].length-2));
              frmObjItem.focus();
              return false;
            }// if
          } // isNaN
        }// if
      }// if
    }// for
  }// with
	return true;
}

function valFCR() {
  with(document.FCRComplaint){
    if(sCustComplaint.value == '') {
      alert('Please enter Customer Complaint');
      sCustComplaint.focus();
      return false;
    }
    if(sTechObservation.value == '') {
      alert('Please enter your Technical Observations');
      sTechObservation.focus();
      return false;
    }
    if(sProbFailure.value == '') {
      alert('Please enter the Probable cause of Failure');
      sProbFailure.focus();
      return false;
    }
    if(sActionTaken.value == '') {
      alert('Please enter the Action taken / Suggestions');
      sActionTaken.focus();
      return false;
    }
    if(sGroupCode.value == '') {
      alert('Please enter the Group Code');
      sGroupCode.focus();
      return false;
    }
    if(sComplaintCode.value == '') {
      alert('Please enter the Complaint Code');
      sComplaintCode.focus();
      return false;
    }
    loading(1);
    document.getElementById('SaveIt').value=1;
    document.FCRComplaint.submit();
    return true;
    
  }
}
function saveFCR(complete) {
  with(document.FCR){
    if(sRepairOrderNo.value != '') {
      if (sRepairOrderDate.value == '') {
        alert('Please enter the Repair Order Date');
        sRepairOrderDate.focus();
        return false;
      }
      if (sRepairCompletion.value == '') {
        alert('Please enter the Repair Completion Date');
        sRepairCompletion.focus();
        return false;
      }
    }
    if (sKmCovered.value == '') {
      alert('Please enter the KMs Covered');
      sKmCovered.focus();
      return false;
    }
  }
  if(confirm('Please make sure your Complaint is saved before saving the FCR.\nDo you wish to continue?')) {
    loading(1);
    getOBJ('CompleteIt',document).value=complete;
    document.FCR.submit();
  }
}

function isCompany(type) {
  if(type==0) { 
    document.getElementById('companyRow1').style.display='none';
    document.getElementById('companyRow2').style.display='none';
    document.getElementById('companyRow3').style.display='none';
  }
  else {
    document.getElementById('companyRow1').style.display='block';
    document.getElementById('companyRow2').style.display='block';
    document.getElementById('companyRow3').style.display='block';
  }
}

function chngValAnImg() {
  field=arguments[0];
  img=arguments[1];
  hide=arguments[2];
  chngTo=arguments[3];
  var fld = getOBJ(field, document);
  var val = fld.value;
  if (val == 1) {
    fld.value = 0;
    changeImg(img, 'images/icons/Approve_Grey_20.gif');
    if (hide != undefined && hide != '') {
      hide.style.display = 'none'; 
    }
    if (document.getElementById('continue') != undefined) {
      document.getElementById('continue').value=parseInt(document.getElementById('continue').value)-1;
    }
  } else { 
    fld.value = 1;
    if (chngTo == undefined) {
      chngTo='Approve_20.gif';
    }
    changeImg(img, 'images/icons/'+chngTo);
    if (hide != undefined && hide != '') {
      if (document.all) {
        hide.style.display = 'block'; 
      } else {
        hide.style.display = 'table-row';
      }
    }
    if (document.getElementById('continue') != undefined) {
      document.getElementById('continue').value=parseInt(document.getElementById('continue').value)+1;
    }
  }
}

function TestNaN(obj,allowPoint)
{
  re = /\./;
  str = obj.value;
  foundPoint = re.test(str);
  if ((allowPoint == '0') && foundPoint) {
    obj.value = 1;
  }
  if (isNaN(obj.value)) {
    obj.value = 1;
  }
  if (obj.value < 0) {
    obj.value = 1;	
  }
}

function checkMSA(num) {
  num += 1;
  if(document.getElementById('MSARef').value == '' || document.getElementById('MSARef').value == 'Dealer No') {
    alert('Enter your Dealer Ref No before submitting');
    return false;
  }
  if (document.getElementById('continue').value == 0) {
    alert('Please select vehicles you would like to order.');
    return false;
  }
  if (document.getElementById('continue').value > num) {
    if(confirm('You have ordered more vehicles than your original order.\nDo you wish to continue?')) {
    } else {
      return false;
    }
  }
  if (document.getElementById('continue').value < num) {
     if(confirm('You have ordered less vehicles than your original order.\nDo you wish to continue?')) {
    } else {
      return false;
    }
  }
  
  document.getElementById('MSARefNo').value=document.getElementById('MSARef').value;
  loading(1);
  document.orderVehicles.submit();
}

function quantity(theQty, up){
  if (up) {
    if (isNaN(theQty.value)){ theQty.value = 1} else {theQty.value++}
  } else {
    if (isNaN(theQty.value) || theQty.value == 0 || theQty.value < 1){theQty.value = 1} else {theQty.value--}
  }  
}

function if0DoThis(field, doThis, elseThis) {
  theCheck = document.getElementById(field);
  if (theCheck.value == 0) {
    theCheck.value = 1;
    t=setTimeout(doThis,1);
  } else {
    theCheck.value = 0;
    t=setTimeout(elseThis,1);
  }
}

function emptyIf(val,field) {
  if(field.value == val ) {
    field.value='';
  }
}

function ShowBox(HTML)
{
 if (HTML != '')
 {
 HTML = HTML.replace('~','"');
 HTML = HTML.replace("^","'");
 if(HTML == null)
 {HTML = "Test"}
 document.all["DefBox"].innerHTML = "<table width=240 cellspacing=1 cellpadding=0 bgcolor=#000000><tr><td><table width=100% bgcolor=#e6e6e6><tr><td><font face=Arial size=1 color=#656565>" + HTML + "<\/font></td></tr></table></td></tr></table>";
 if (event.x - 15 + 225 < document.body.offsetWidth)
 {
 document.all["DefBox"].style.left = event.x - 100;
 }
 else
 {
 document.all["DefBox"].style.left = document.body.offsetWidth - 225;
 }
 document.all["DefBox"].style.top = event.y + 15 + document.body.scrollTop;
 document.all["DefBox"].style.visibility = "visible";
 }
}
function HideBox()
{
 document.all["DefBox"].style.visibility = "hidden";
}