/**
 * Generic JS functions
 * used site wide
 */

/**
 * Generic confirmation message
 * @param string linkPath
 * @param string cfmMsg
 */
function confirmAction(linkPath,cfmMsg,urlType,formNm){
	
	switch(urlType){
		case 'hLink': 
			//hyperlink
			if (confirm(cfmMsg)){
				document.location.href= linkPath;
			}
		break;
		case 'fLink':
			//form link
			if (confirm(cfmMsg)){
				document.forms[formNm].submit();
			}
		break;
		default:
			return false;
	}
	return false;
}

//tek 01.15.01
//Validates the phone number is a valid phone number in either the format with 123-1234 or 123-123-1234
function ckPhone(obj)
{

  var indexofdash = obj.value.indexOf("-",0);
  var lastindex = obj.value.lastIndexOf("-",obj.value.length-1);
  var firstthree;
  var secondthree;
  var lastfour;


  //First check to ensure a valid number is entered
 //check to see if no dashes are entered and it is a fully numeric number
  if ((isNaN(obj.value)) && (indexofdash == -1))
    {
        alert("The phone number must be numeric");
        obj.value = "";
        obj.focus();
        return;
    }
//check to see if a 10 digit number is entered without dashes
  if ((indexofdash == -1) &&  (obj.value.length == 10))
  {
    firstthree = obj.value.substring(0,3);
    secondthree = obj.value.substring(3,6);
    lastfour = obj.value.substring(6,10);

  }
//check to see if a 7 digit number is entered without dashes
  else if ((indexofdash == -1) && (obj.value.length == 7))
  {
    secondthree = obj.value.substring(0,3);
    lastfour = obj.value.substring(3,7);

  }
//returns if a 7 digit number with one dash in the 4th position is entered
  else if ((obj.value.length == 8) && (indexofdash == 3))
  {
    secondthree = obj.value.substring(0,3);
    lastfour = obj.value.substring(4,8);
    if ((isNaN(secondthree)) || (isNaN(lastfour)))
    {
        alert("The phone number must be numeric");
        obj.value = "";
        obj.focus();
        return;
    }
    return;
  }
  //returns if a 10 digit number with a dash in the 4th position and a dash in the 8th position are entered
  else if ((obj.value.length == 12) && (indexofdash == 3) && (lastindex == 7))
  {
    firstthree = obj.value.substring(0,3);
    secondthree = obj.value.substring(4,7)
    lastfour = obj.value.substring(8,12)
    if ((isNaN(firstthree)) || (isNaN(secondthree)) || (isNaN(lastfour)))
    {
        alert("The phone number must be numeric");
        obj.value = "";
        obj.focus();
        return;
    }
    return;
  }
  else if (obj.value.length == 0)
  {
    return;
  }
  else
  {
    alert("This is not a valid phone number");
    obj.value = "";
    obj.focus();
    return;
  }
  if (firstthree != null)
  {
     obj.value = firstthree + "-" + secondthree + "-" + lastfour;
  }
  else
  {
     obj.value = secondthree + "-" + lastfour;
  }

}

//tek 01.15.01
//Validates the zip code is a valid number in the format 12345
function ckZip(obj)
{
//check to see if 5 characters are entered
  if((obj.value.length < 5) && (obj.value.length != 0))
  {
    alert("You must enter at least 5 digits of the zip code");
    obj.value = "";
    obj.focus();
    return;
  }



  //Then check to ensure a valid number is entered
  if (isNaN(obj.value))
    {
        alert("The zip code must be numeric");
        obj.value = "";
        obj.focus();
        return;
    }
}
//jas 06.07.02
// function to validate email address
function ckEmail(obj)
{
  if(obj.value.length == 0)
  {
    return;
  }
  for(i=0; i< obj.value.length; i++) {
    if (obj.value.substring(i,i+1) == "@")
      break;
  }
  if ( i >= (obj.value.length - 1))
  {
    alert('The email address must contain @ to be valid');
    obj.value = "";
    obj.focus();
    return;
  }
   for (j = i; j< obj.value.length; j++) {
    if (obj.value.substring(j,j+1) == ".")
    break;
  }
  if ( j >= (obj.value.length -1) )
  {
    alert('Missing .com or .net of address');
    obj.value = ""
    obj.focus();
    return;
  }
}

//----------------------------------
function mand(obj){
//----------------------------------
	var str = obj.value;
	if(str == null || str.length == 0){
		alert('This field is required.');
		obj.focus();
		return false;
	}
	else{
		return true;	
	}
}
//----------------------------------
function isEmailAddr(obj){
//----------------------------------
	var str = obj.value;
	var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
	if(!str.match(re)){
		alert("Email address entered appears to be invalid. Please check to make sure you typed it correctly.");
		return false;
	}else{
		return true;
	}
}

//Validates the zip code is a valid number in the format 12345
//---------------------------------
function ckZip(obj){
//---------------------------------
//check to see if 5 characters are entered
  if((obj.value.length < 5) && (obj.value.length != 0))
  {
    alert("You must enter at least 5 digits of the zip code");
    obj.value = "";
    obj.focus();
    return;
  }

  //Then check to ensure a valid number is entered
  if (isNaN(obj.value))
    {
        alert("The zip code must be numeric");
        obj.value = "";
        obj.focus();
        return;
    }
}

//--------------------------------
function isUrl(obj) {
//--------------------------------
	var regexp = new RegExp("((http|https)(:\/\/))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(\/{1}[a-zA-Z0-9]+)*\/?", "i");
	if(obj.value.length == 0){
    	return;
	}
	//skip validation with internal links
	if($('#attach_type')){
		if($('#attach_type').val() == 'iLink'){
			return;	
		}
	}
	if(obj.value.length < 3){
		alert('Please enter a valid web address');	
		obj.focus();
	}
	if(!regexp.test(obj.value)){
		alert('The web address entered does not appear to be valid.');	
		obj.focus();
	}
	return;
}
//---------------------------------
function ckDate(ev) {
//---------------------------------
  
      isAllValid = false
 
   
   vdt = ev.value
//   if (vdt.length == 0)
//      return
//   if (vdt == "mm/dd/yyyy")
//      return
      
  // parse date
   if (vdt.length > 0)
   {
   dts = vdt.split("/",4)
   j = dts.length
   
   if (j != 3)
   {
      curTarget = ev
      inEvent = true
      alert("Error: Date must be in the format MM/DD/YYYY")
      ev.value='';
      ev.focus()
      isAllValid = false
      return
   }
   else
   {
      mon = dts[0] - 0
      if (isNaN(mon) == true)
      {
         curTarget = ev
         inEvent = true
         alert("Error: Invalid Month")
         ev.value='';
         ev.focus()
         isAllValid = false
         return
      }
      if (mon < 1 || mon > 12)
      {
         curTarget = ev
         inEvent = true
         alert("Error: Invalid Month")
         ev.value='';
         ev.focus()
         isAllValid = false
         return
      }
     
      day = dts[1] - 0
      if (isNaN(day) == true)
      {
         curTarget = ev
         inEvent = true
         alert("Error: Invalid Day")
         ev.value='';
         ev.focus()
         isAllValid = false
         return
      }
      yr = dts[2] - 0
      if (isNaN(yr) == true || yr < 1000)
      {
         curTarget = ev
         inEvent = true
         alert("Error: Invalid Year - Use Date format MM/DD/YYYY");
         ev.value='';
         ev.focus()
         isAllValid = false
         return
      }
      switch(mon)
      {
         case 1:
         case 3:
         case 5:
         case 7:
         case 8:
         case 10:
         case 12:
            if (day < 1 || day > 31)
            {
               curTarget = ev
               inEvent = true
               alert("Error: Invalid Day")
               ev.value='';
               ev.focus()
               isAllValid = false
               return
            }
            break
         case 4:
         case 6:
         case 9:
         case 11:
            if (day < 1 || day > 30)
            {
               curTarget = ev
               inEvent = true
               alert("Error: Invalid Day")
               ev.value='';
               ev.focus()
               isAllValid = false
               return
            }
            break
         default:
            lpyr = 0
            if (yr < 100)
               yr += 1900
            if (yr % 4 == 0)
            {
               if (yr % 100 != 0)
                  lpyr = 1
               else if (yr % 400 == 0)
                  lpyr = 1
            }
            if (day < 1 || day > (28 + lpyr))
            {
               curTarget = ev
               inEvent = true
               alert("Error: Invalid Day")
               ev.value='';
               ev.focus()
               isAllValid = false
               return
            }
      }
   }
   }
}
// --- Code for Board news and Bulletin Board Maintenance ---
//  added: 7/23/04 LP
//  If they enter a date in the past it changes it to tomorrow.
//
//  indate = date entered
//  fldname = name on the search form where they entered the date.
//
function ChkFutDt(indate, effdate)
{
    var today = new Date();
  infield1 = indate.value;
  infield2 = effdate.value;
    sentdate = new Date(indate.value);
    sentdate2 = new Date(effdate.value);
//  var todayms = today.getTime();
    var indatems = sentdate.getTime();
    var effdatems = sentdate2.getTime();
    var mm = today.getMonth() + 1;
    var dd = today.getDate();
    var yyyy = today.getFullYear();
    todaysdt = mm + '/' + dd + '/' + yyyy;
  var todaydt = new Date();
  todaydt.setHours(0);
  todaydt.setMinutes(0);
  todaydt.setSeconds(0);
  todaydt.setMilliseconds(0);
    //When data is in both fields
    //Expire date entered only
    if (infield1 != "" && infield2 == "")
    {
        if (indatems < todaydt)
        {
            alert("Expire Date is in the past, Please enter a future date");
            indate.value = todaysdt;
      setTimeout(function(){indate.focus();},1);
        }
    return;
    }
    //Effective date entered only
    if (infield1 == "" && infield2 != "")
    {
        if (effdatems < todaydt)
        {
            alert("Effective Date is in the past, Please enter a future date");
            effdate.value = todaysdt;
      setTimeout(function(){effdate.focus();},1);
        }
    return;
    }
    if (indatems < todaydt)
        {
            alert("Expire Date is in the past, Please enter a future date");
            indate.value = todaysdt;
      setTimeout(function(){indate.focus();},1);
      return;
        }

    if (effdatems < todaydt)
        {
            alert("Effective Date is in the past, Please enter a future date");
            effdate.value = todaysdt;
      setTimeout(function(){effdate.focus();},1);
      return;
        }

    if (effdatems > indatems)
        {
            alert("Effective Date is after Expire Date");
            indate.value = "";
            effdate.value = "";
      setTimeout(function(){effdate.focus();},1);
        }
return;
}
/**
 * generic image edit functions
 */
var Misc = new function() {
	this.oldButnText = '';
	//delete a image from the attachment table
	this.deleteImage = function(imageId,fileName) {
		var self = Misc;
		if (confirm ('Are you sure you wish to delete this image?')) {
			$.ajax({ url      : site_base_url+"/misc/deleteImage", 
					 data     : 'id='+imageId+'&file='+fileName,
					 dataType : "json",
					 type     : 'POST',
					 success  : function(result){
						if ('status' in result) {
							if (result.status == 'success') {
								$('#imgContainer_'+imageId).slideUp('slow',function() {
									$(this).empty();
									
								});
							}
							if (result.status == 'error') {
								alert(result.message);
							}
						}												
					 },
					 error    : function(){
						 alert('An unknown error occured while deleteing this image. Please try again.');
					 }
			});
		}
	};
	//load an image into the attachment table input form
	this.imageLoad = function(imageId,align) {
		var self = Misc;
		$.colorbox({transition:"elastic", innerWidth:"500px", inline:true, href:"#attachFormContainer"});
		if (imageId != '') {
			//edit
			$('#addEdit').html('Edit');
			$('#imgUploadButn').val('Edit Image');
			$('#attachForm').find('label[for="attachment"]').html('Image:');
			$('#attach_align').find("option[value=" + align + "]").attr("selected", "selected");
			$('#attach_id').val(imageId);
			var label = $('#imgContainer_'+imageId).find('img').attr('alt');
			var img = $('#imgContainer_'+imageId).find('img').attr('src');
			$('#attach_label').val(label);
			$('#addEdit').append('<span style="float:right;position:relative;"><img src="'+img+'" height="26" width="36" /></span>');
		} else {
			//add
			$('#addEdit').html('Add');
			$('#imgUploadButn').val('Attach Image');
			$('#attachForm').find('label[for="attachment"]').html('Image:<em><img src="'+site_url+'/img/requiredStar.gif" alt="Required" /></em>');
			$('#attach_label').val('');
			$('#attach_id').val('');
		}
		//clear file field
		$('#fileUplHolder').html('<input type="file" name="userfile" value="" id="attachment"  />');
	};
	//submit an image to the attachment table
	this.imageSubmit = function() {
		var self = Misc;
		self.oldButnText = $('#imgUploadButn').val();
		$('#imgUploadButn').val('Please Wait.');
		
		//create iframe
		$("<iframe style='display:none;' id='iFrame' name='iFrame' src='javascript:false;'></iframe>").appendTo('#iFrameHolder');
        $('#attachForm').attr('target','iFrame');
			
		//submit form
		$('#attachForm').submit();
	};
	//handle submit result
	this.submitResult = function(result) {
		var self = Misc;
		//console.log(result);
		var res = result.replace(/^\s*|\s*$/g,"");
		if(res != ''){
			var respArr  = res.split('|');
            var respType = respArr[0].toLowerCase();
			var message  = respArr[1];
			var attId    = respArr[2];
			var attName  = respArr[3];
			var attUrl   = respArr[4];
			var sysPth   = respArr[5];
			
			if (respType == 'success') {
				//var newImg = '<span id="imgContainer_44" style="position:relative;float:right;">'						 
				//$('#imgContainer_0').before(newImg);
				document.location.href=document.location.href;
				$.colorbox.close();
			} else {
				$('#attachMsg').html(message)
				.delay(6000).slideUp();
			}
		} else {
			alert('An unknown error occured.');
			$.colorbox.close();
		}
		//reset
		$('#imgUploadButn').val(self.oldButnText);
		$('#iFrameHolder').html('');
	};
};
 
/**
function genericDeleteImage(imageId) {
	
}
function genericEditImageForm(clickedObj,attachTable,tableId,attachId,action) {
	if (action == '') {
		return;
	}
	var origClickText = $(clickedObj).val();
	$(clickedObj).val('Please Wait');
	
	var imgContainer = '';
	if (action == 'add') {
		imgContainer = $('#imgContainer_0').html();
		$('#imgContainer_0').html(imageForm(0,'Add'));
	}
	if (action == 'edit') {
		imgContainer = $('#imgContainer_'+attachId).html();
		$('#imgContainer_'+attachId).html(imageForm(attachId,'Edit'));
	}
	
}
function imageForm(attachId,type,tableId) {
	return "<div style='padding:5px; background:#ccc;'>"
          + "<h4>"+type+" Image</h4>"
		  + "<form action='"+site_base_url+"/misc/imageForm' name='attachForm' id='attachForm' enctype='multipart/form-data'>"                        
          + "	 <fieldset>"
          + "    <input type='hidden' name='attach_table' id='attach_table' value='misc' />"
          + "    <input type='hidden' name='attach_table_id' id='attach_table_id' value='"+tableId+"' />"
          + "    <input type='hidden' name='attach_type' id='attach_type' value='file' />"
          + "        <div id='attachMsg'></div>"
          + "        <div id='fileUplHolder'><input type='file' name='userfile' value='' id='attachment' /></div>"
          + "        <span class='small'>Images must be type 'JPG' and be less than 3mb.</span>"                   
		  + "        <label for='img_title'>Image Title:<em><img src='"+site_base_url+"/img/requiredStar.gif' alt='Required' /></em></label>"
		  + "        <input type='text' name='img_title' value='' id='img_title' size='50' maxlength='255' />"
		  + "        <label for='img_align'>Alignment:<em><img src='"+site_base_url+"/img/requiredStar.gif' alt='Required' /></em></label>"
		  + "        <select name='img_align' id='img_align'><option value='left'>Left</option><option value='right'>Right</option></select>"
          + "    </fieldset>"
          + "    <fieldset class='submit'>"
          + "        <input type='button' id='uploadButn' value='Attach Image' class='normButn green' onclick='imageSubmit()' />"
          + "    </fieldset>"
          + "</form>"
          + "<div id='iFrameHolder'></div>"         
          + "</div>";
}
**/
