// JavaScript Document
var intervalCounter = 0;
$(function() {
  if ($('#Manufacturer').length > 0 && $('#TechSpecs').length > 0){pageEventTracker('Details','Chrome','Has Chrome Tabs');}
  if ($('#PhotoVideo').length > 0){pageEventTracker('Details','Photo Video','Has PhotoVideo Tab');}
  if ($('#Video').length > 0){pageEventTracker('Details','YouTube Video','Has YouTube Tab');}

  $('#tab_Photo').click(function(){pageEventTracker('Details','Photo Tab',$('#hLabel').val());});
  $('#tab_PhotoVideo').click(function(){pageEventTracker('Details','PhotoVideo Tab',$('#hLabel').val());});
  $('#tab_Youtube').click(function(){pageEventTracker('Details','YouTube Tab',$('#hLabel').val());});
  $('#tab_General').click(function(){pageEventTracker('Details','General Tab',$('#hLabel').val());});
  $('#tab_Manufacturer').click(function(){pageEventTracker('Details','Manufacturer Options Tab',$('#hLabel').val());});
  $('#tab_TechSpecs').click(function(){pageEventTracker('Details','Tech Specs Tab',$('#hLabel').val());});
  
  $("#tabs").tabs();
	var $PhotoTabs = $("#phototabs").tabs({
	 select: function (e,ui) {
     if (ui.tab.id == '') {
       $('.photoTabText').show();
     } else {
       $('.photoTabText').hide();
     }
	   return true;
   }
	});
  $('#playButton').click(function() {
    var iTabIndex = 0;
    $('#tabs2 ul li a').each(function(i) {if (this.id == 'PhotoVideoLink') {iTabIndex = i}});
    $PhotoTabs.tabs('select', iTabIndex);
    document.location.href="#phototabs";
    pageEventTracker('Video','AutoConX Video Play Button (Details)',$('#hLabel').val());
    return false;
  });	
  
  $('#playButton_YouTube').click(function() {
    var iTabIndex = 0;
    $('#tabs2 ul li a').each(function(i) {if (this.id == 'YouTubeVideoLink') {iTabIndex = i}});
    $PhotoTabs.tabs('select', iTabIndex);
    document.location.href="#phototabs";
    pageEventTracker('Video','YouTube Video Play Button (Details)',$('#hLabel').val());
    return false;
  }); 

  $('#playButton_iframeVideo').click(function() {
    var iTabIndex = 0;
    $('#tabs2 ul li a').each(function(i) {if (this.id == 'iframeVideoLink') {iTabIndex = i}});
    $PhotoTabs.tabs('select', iTabIndex);
    document.location.href="#phototabs";
    pageEventTracker('Video','External Video Play Button (Details)',$('#hLabel').val());
    return false;
  }); 
  
  $('#liframeVideo').click(function() {
    var iTabIndex = 0;
    $('#tabs2 ul li a').each(function(i) {if (this.id == 'iframeVideoLink') {iTabIndex = i}});
    $PhotoTabs.tabs('select', iTabIndex);
    document.location.href="#phototabs";
    pageEventTracker('Video','External Video Toolbox Link (Details)',$('#hLabel').val());
    return false;
  }); 
  
  
  
  $('#lPhotoVideo').click(function() {
    var iTabIndex = 0;
    $('#tabs2 ul li a').each(function(i) {if (this.id == 'PhotoVideoLink') {iTabIndex = i}});
    $PhotoTabs.tabs('select', iTabIndex);
    document.location.href="#phototabs";
    pageEventTracker('Video','AutoConX Video Toolbox Link (Details)',$('#hLabel').val());
    return false;
  }); 
  $('#lYoutube').click(function() {
    var iTabIndex = 0;
    $('#tabs2 ul li a').each(function(i) {if (this.id == 'YouTubeVideoLink') {iTabIndex = i}});
    $PhotoTabs.tabs('select', iTabIndex);
    document.location.href="#phototabs";
    pageEventTracker('Video','YouTube Toolbox Link (Details)',$('#hLabel').val());
    return false;
  }); 
  $('#lPhotoLink').click(function() {
    $PhotoTabs.tabs('select', 0);
    document.location.href="#phototabs";
    pageEventTracker('Photos','Photos Toolbox Link (Toolbox)',$('#hLabel').val());
    return false;
  });
	$('#lMakeOffer').click(function(){
	  $("#PaymentEstimator").slideUp('slow');
	  $("#EmailToFriend").slideUp('slow');
	  $("#EmailSeller").slideUp('slow');
	  $("#MakeOffer").slideDown('slow');
	  pageEventTracker('Details','Make an Offer Link (Toolbox)',$('#hLabel').val());
	  $('#moef_Firstname').focus();
	});
	$('#lMoreInfo').click(function(){
	  $("#MakeOffer").slideUp('slow');
	  $("#EmailToFriend").slideUp('slow');
	  $("#PaymentEstimator").slideUp('slow');
	  $("#EmailSeller").slideDown('slow');
    pageEventTracker('Details','Request more information Link (Toolbox)',$('#hLabel').val());
    $('#ef_Firstname').focus();
	});
	$('#lMoreInfo2').click(function(){
	  $("#MakeOffer").slideUp('slow');
	  $("#EmailToFriend").slideUp('slow');
	  $("#PaymentEstimator").slideUp('slow');
	  $("#EmailSeller").slideDown('slow');
    pageEventTracker('Details','Email the Seller (Button)',$('#hLabel').val());
	});
	$('#lPaymentCalc').click(function(){
	  $("#MakeOffer").slideUp('slow');
	  $("#EmailToFriend").slideUp('slow');
	  $("#EmailSeller").slideUp('slow');
	  $("#PaymentEstimator").slideDown('slow');
    pageEventTracker('Details','Calculate Payment (Toolbox)',$('#hLabel').val());
	});
	$('#lEmailToFriend').click(function(){
	  $("#MakeOffer").slideUp('slow');
	  $("#PaymentEstimator").slideUp('slow');
	  $("#EmailSeller").slideUp('slow');
	  $("#EmailToFriend").slideDown('slow');
    pageEventTracker('Details','Email to Friend (Toolbox)',$('#hLabel').val());
	});
	$('#lFinance').click();
	$('#EmailForm').validate({
	  debug:false,
	  errorElement: "div",
	  errorLabelContainer: "#messageBox",
    /*
    showErrors: function(errorMap, errorList) {
      $("#errorHolder").html("The fields marked in red are required or have errors.").addClass('error');
      this.defaultShowErrors();
    },
    */
    messages: {
      'FirstName_First.Name_txt_t': {required: translate.First_Name_is_a_required_field},
      'LastName_Last.Name_txt_t': {required: translate.Last_Name_is_a_required_field},
      'MailFrom_Email_email_t': {required: translate.Email_is_a_required_field, email:translate.Please_enter_a_valid_email_address},
      'Phone_Phone_phone_f': {required:translate.Phone_is_a_required_field, phoneUS:translate.Please_enter_a_valid_phone_number},
      'zip_zip.code_zipcode_f': {required:translate.Zip_Code_is_a_required_field},
      'Code_Code_txt_t': {required:translate.Verification_Code_is_a_required_field, minlength:translate.Please_enter_the_three_character_verification_code}      
    },
    rules: {
      'Code_Code_txt_t': {required: true,minlength: 3}
    }
	});
	$('#EmailFriendForm').validate();
	$('#MakeOfferEmailForm').validate({
    debug:false,
    errorElement: "div",
    errorLabelContainer: "#messageBoxOffer",
    /*
    showErrors: function(errorMap, errorList) {
      $("#errorHolder").html("The fields marked in red are required or have errors.").addClass('error');
      this.defaultShowErrors();
    },
    */
    messages: {
      'FirstName_First.Name_txt_t': {required: translate.First_Name_is_a_required_field},
      'LastName_Last.Name_txt_t': {required: translate.Last_Name_is_a_required_field},
      'MailFrom_Email_email_t': {required:translate.Email_is_a_required_field, email:translate.Please_enter_a_valid_email_address},
      'Phone_Phone_phone_f': {required:translate.Phone_is_a_required_field, phoneUS:translate.Please_enter_a_valid_phone_number},
      'zip_zip.code_zipcode_f': {required:translate.Zip_Code_is_a_required_field},
      'Code_Code_txt_t': {required:translate.Verification_Code_is_a_required_field, minlength:translate.Please_enter_the_three_character_verification_code},
      'offer_Offer_txt_t':{required:'Offer is a required field.'}      
    },
    rules: {
      'Code_Code_txt_t': {required: true,minlength: 3}
    }
	});
	$('#LoanCalculatorForm #btnCalculate').click(function () {fnCalculateLoan();})
	$('#EmailForm #ef_Phone').mask('(999)999-9999');
	$('#MakeOfferEmailForm #MOEF_Phone').mask('(999)999-9999');

	fnCollectStats = function() {
    var iInventoryID = $('#hID').val();
    var iVerticalSiteID = $('#hVSID').val(); 
    var iVerticalLocationID = $('#hLID').val();
	  var iMathVerification = 5+5;
    $.ajax({
      type: "GET",
      url: "/components/StatsCollector.cfc",
      dataType: "xml",
      data: "method=fnCountStats&iInventoryID="+iInventoryID+"&iVerticalSiteID="+iVerticalSiteID+"&iVerticalLocationID="+iVerticalLocationID+"&iMathVerification="+iMathVerification
    });    
  };
  if ($('#hID').val() != undefined) {
    fnCollectStats();
  }

	$('#WebsiteClicks').click( function() {
		var iDealerID = $("#hDID").val();
		var iVerticalSiteID = $("#hVSID").val();
		var iVerticalLocationID = $("#hLID").val();
		var sIPAddress = $("#hHip").val();
		$.ajax ({
			type:"GET",
      url: "/components/StatsCollector.cfc",
      dataType: "xml",
			data: "method=fnCountWebsiteClicks&iDealerID="+iDealerID+"&iVerticalSiteID="+iVerticalSiteID+"&iVerticalLocationID="+iVerticalLocationID+"&sIPAddress="+sIPAddress
		});
	});	

  $('#flagitem').click( function() {
    var iInventoryID = $('#hID').val();
    var iVerticalSiteID = $("#hVSID").val();
    var iVerticalLocationID = $("#hLID").val();
    var sIPAddress = $("#hHip").val();
    var iMathVerification = 5+5;
    $.ajax ({
      type:"GET",
      url: "/components/FlagItem.cfc",
      dataType: "text",
      data: "method=fnFlagItem&iInventoryID="+iInventoryID+"&iMathVerification="+iMathVerification,
      success: function(text){$('#flagcontainer').text(translate.This_item_has_been_flagged);}
    });
  }); 


  if (location.hash == '#video') {
    var iTabIndex = 0;
    $('#tabs2 ul li a').each(function(i) {if (this.id == 'PhotoVideoLink') {iTabIndex = i}});
    $PhotoTabs.tabs('select', iTabIndex);
    document.location.href="#phototabs";
  }

  startPhotoProcessor();
  timerPhotoCheck = setInterval('photoCheck()', 1000);
});

  function startPhotoProcessor(){
    var Server = $('#hServer').val();
    var ProcessPhotos = $('#hProcessPhotos').val();
    var ID = $('#hID').val();
    if (ProcessPhotos == 1){
      $.ajax ({
        type:"GET",
        url: "/components/images.cfc",
        dataType: "text",
        data: "method=startProcessing&ID="+ID+"&serverNumber="+Server,
        success: function(text){}
      })
    }
  }


  function photoCheck() {
    var Server = $('#hServer').val();
    var PhotosAvailable = $('#hPhotosAvailable').val();
    var ProcessPhotos = $('#hProcessPhotos').val();
    var ID = $('#hID').val();
    var oTbody = '<tr>';
    var photoCount = 0;
    if (ProcessPhotos == 0 || intervalCounter > 59){
      clearInterval(timerPhotoCheck);
    } else {
      $.ajax ({
        type:"GET",
        url: "/components/images.cfc",
        dataType: "text",
        data: "method=GetCount&ID="+ID+"&serverNumber="+Server,
        success: function(text){
          photoCount = parseInt(text);
          if (photoCount > 0){
            for (i = 1; i <= photoCount; i++){
              $('#currentphoto').html('Photo 1 of ' + i)
              oTbody += '<td style="height:75px; width:100px;"><a href="javascript:void(0);" onclick="fnEnlargeImage('+ID+','+i+','+photoCount+'); return false;"><img src="'+ imageServer +'?ID='+ ID +'&idx='+ i +'&w=100&h=75" /></a></td>'
              if (i%7 == 0){oTbody += '</tr><tr>';}
            }
            if (PhotosAvailable > photoCount){
              oTbody += '<td style="height:75px; width:100px; text-align:center;"><img src="/images/loading3.gif" /><div>Loading Photos</div></td>'
              if ((photoCount-1)%7 != 0){
                for (j = 1; j <= (7-(photoCount%7))-1; j++) {
                  oTbody += '<td style="height:75px; width:100px;">&nbsp;</td>'        
                }
              }              
            } else if (photoCount%7 != 0){
              for (j = 1; j <= (7-(photoCount%7)); j++) {
                oTbody += '<td style="height:75px; width:100px;">&nbsp;</td>'        
              }
            }
            
          }
          oTbody += '</tr>';
          $('#photoThumbHolder').html(oTbody);
          $('#_NextPrevHolder').html('&laquo; <a id="_imagePrev" class="nextPrev" href="javascript:void(0);" onclick="fnPrevImage('+ ID +','+ photoCount +'); return false;">'+ translate.Prev_Photo +'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a id="_imageNext" class="nextPrev" href="javascript:void(0);" onclick="fnNextImage(' + ID + ',' + photoCount + '); return false;">'+ translate.Next_Photo+'</a> &raquo;');
          if (PhotosAvailable == photoCount) {
            clearInterval(timerPhotoCheck);  
          }
        }
      });
    }
    intervalCounter++
  }


function checkNum(data) {      // checks if all characters 
	var valid = "0123456789.";     // are valid numbers or a "."
	var ok = 1; var checktemp;
	for (var i=0; i<data.length; i++) {
		checktemp = "" + data.substring(i, i+1);
		if (valid.indexOf(checktemp) == "-1") 
			return 0; 
	}
	return 1;
}
    
function dollarAmount(number) { // idea by David Turley
	Num = "" + eval(number);
	dec = Num.indexOf(".");
	end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : ".00");
	Num = "" + parseInt(Num);
	var temp1 = "";
	var temp2 = "";
	if (checkNum(Num) == 0) {
		alert(translate.invalid_number);
	}
	else { 
		if (end.length == 2) 
			end += "0";
		if (end.length == 1) 
			end += "00";
		if (end == "") 
			end += ".00";
		var count = 0;
		for (var k = Num.length-1; k >= 0; k--) {
			var oneChar = Num.charAt(k);
			if (count == 3) {
				temp1 += ",";
				temp1 += oneChar;
				count = 1;
				continue;
			}
			else {
				temp1 += oneChar;
				count ++;
			}
		}
		for (var k = temp1.length-1; k >= 0; k--) {
			var oneChar = temp1.charAt(k);
			temp2 += oneChar;
		}
		temp2 = "$" + temp2 + end;
		return " " + temp2;
	}
}
function fnCalculateLoan() {
	var princ = document.LoanCalculatorForm.price.value - document.LoanCalculatorForm.downpayment.value;
	var term  = document.LoanCalculatorForm.term.value;
	if (document.LoanCalculatorForm.rate.value == 0) {
		var intr   = 0.0000001 / 1200;
	} else {
		var intr   = document.LoanCalculatorForm.rate.value / 1200;
	}
	document.getElementById('monthlypayment').innerHTML = dollarAmount(Math.round(princ * intr / (1 - (Math.pow(1/(1 + intr), term)))*100)/100);
}

function fnEnlargeImage(ID,CurrentImage,PhotoCount) {
	document.getElementById('BigImage').src = imageServerBase + '/Photos/'+Right(ID,3)+'/'+ID+'_'+CurrentImage+'_b.jpg';
	document.getElementById('currentphoto').innerHTML = CurrentImage+' of ' + PhotoCount;
}

function fnNextImage(ID,PhotoCount) {
	var CurrentImage = document.getElementById('BigImage').src.split("_");
	var NextImage = parseInt(CurrentImage[1]) + 1;
	var d = new Date();
	if (NextImage <= PhotoCount) {
		document.getElementById('BigImage').src = imageServerBase + '/Photos/'+Right(ID,3)+'/'+ID+'_'+NextImage+'_b.jpg?rand='+d.getTime();
		document.getElementById('currentphoto').innerHTML = NextImage + ' of ' + PhotoCount;
	}
	else {
		document.getElementById('BigImage').src = imageServerBase + '/Photos/'+Right(ID,3)+'/'+ID+'_1_b.jpg?rand='+d.getTime();
		document.getElementById('currentphoto').innerHTML = '1 of ' + PhotoCount;
	}
}


function fnPrevImage(ID,PhotoCount) {
	CurrentImage = document.getElementById('BigImage').src.split("_");
	NextImage = parseInt(CurrentImage[1]) - 1;
	var d = new Date();
	if (NextImage >= 1) {
		document.getElementById('BigImage').src = imageServerBase + '/Photos/'+Right(ID,3)+'/'+ID+'_'+NextImage+'_b.jpg?rand='+d.getTime();
		document.getElementById('currentphoto').innerHTML = NextImage + ' of ' + PhotoCount;
	}
	else {
		document.getElementById('BigImage').src = imageServerBase + '/Photos/'+Right(ID,3)+'/'+ID+'_'+PhotoCount+'_b.jpg?rand='+d.getTime();
		document.getElementById('currentphoto').innerHTML = PhotoCount + ' of ' + PhotoCount;
	}
}
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

