$(function() {
  if ($('a.lightbox').length) $('a.lightbox').lightBox();
  
  if ($('#type').length > 0) {
   // var filename = MAIN_URL+escape("/give/GiveStaticData?type=subcat&cat=" + $('#type').val());
   // $("#subtype").load(filename);
   Global.loadAction("#subtype", "GiveStaticData", {type: 'subcat', cat : $("#type").val(),subtype : $('#hidsubtype').val()});
  }

  if ($('#section_raised').length >0) {
     $('#amount').animate({"width": $("#graph_value").text()});
  }

  // Handle navigation dropdowns with selected states and also by adding .hover for IE6.
  // Make the dropdown re-appear after a short delay on mouseout.
  var selected_nav = $("#nav > li.selected");
  var selected_to = null;
  var selected_delay = 100;
  $('#nav > li').hover(
    function () {
      clearTimeout(selected_to);
      var this_li = this;
      $(selected_nav).each(function() {
        if (this != this_li) {
          $(selected_nav).removeClass("selected");
        }
      });
      $(this).addClass('hover');
    },
    function () {
      clearTimeout(selected_to);
      var this_li = this;
      $(selected_nav).each(function() {
        var select_nav = function() {
          $(selected_nav).addClass("selected");
        };
        if (this != this_li) {
          selected_to = setTimeout(select_nav, selected_delay);
        } else {
          select_nav();
        }
      });
      $(this).removeClass('hover');
    }
  );

  // Section-specific code

  if ($("body.home").length > 0) {
    var flashvars = {
                    mainUrl: MAIN_URL+"/",
                    giveUrl: MAIN_URL_SSL+"/give/donate/"
                    };
    var params = {wmode: "transparent", bgcolor: "#00FF00"};
    swfobject.embedSWF("./swf/home-featured.swf", "feature_obj", "900", "240", "9.0.115", "", flashvars, params);
  }

  if ($("body.give #content.donate").length > 0) {
    FormUtils.drawPaymentFields();
    FormUtils.manageDonateReason();	    
    $("#cvv2_info").tooltip({
                            showURL: false,
                            showBody: "|"
                            });

    $("#deselect").click(function() {
      $("input[name=reason]").removeAttr('checked');
      $('#deselect_row').hide();
      FormUtils.manageDonateReason();
    });

    $('input[name=amount_110]').click(function() {
      FormUtils.togglePaymentMode('nonrec');
    });

    $('input[name=amount_month]').click(function() {
      FormUtils.togglePaymentMode('rec');
    });

    $("input[name=reason]").click(function() {
      FormUtils.manageDonateReason();
    });

    $("input[name=payment_method]").click(function() {
      FormUtils.drawPaymentFields()
    });
    
    //if donation is getting processed show modal dialog;
    
    $("input[name=Submit]").click(function(){
    		$("#processing_dialog").dialog({
						bgiframe: true,
						height: 150,
						modal: true
					});
    });
  }

   // handle hint text in register for updates
   $("#register ul input[type=text]").focus(function() {
        if ($(this).attr("id") == "") {
          $(this).attr("id",$(this).val());
          $(this).blur(function() {
            if (($(this).val() == "") && ($(this).attr("id")!= "")) {
              $(this).val($(this).attr("id"));
              $(this).addClass("hint");
            }
          });
        }
      if ($(this).val() == $(this).attr("id")) {
        $(this).val("");
        $(this).removeClass("hint");
      }
    });

  $('.paths #feature ol a').click(function () {
      $('#popup_maincontainer').attr('class','popup '+$(this).attr('class'));
      $('#popup_content').text('Loading...');
	  $('.popup').show();
	  Global.loadAction("#popup_maincontainer", "WorkPopUp", {type: this.id}, function() { });
      return false;
  });

  $('.popup .close').live("click", function () {
    $('.popup').hide();
    return false;

  });

  //if 'other' text box is clicked radio selection will be changed//handled below
  $('#amount_110_other').focus(function(){
      $("input[name=amount_110]:last").attr('checked','checked');
      $("[name='amount_month']").removeAttr('checked');
      $('#amount_month_other').val('');
  });
  $('#amount_month_other').focus(function(){
      $("input[name=amount_month]:last").attr('checked','checked');
      $("[name='amount_110']").removeAttr('checked');
      $('#amount_110_other').val('');
  });
  $('#other').focus(function(){
      $("input[name=amount]:last").attr('checked','checked');
  });

 //Calculating total amount of tickets & additional donation  
  $("#additional_donation").keyup(function() {
 		var total= 0.0;
 		var numberOfTickets = 0;
 		$("#donation_info select").each(function() {
			
 			if ($(this).val() != '') {
 			  var temp = new Array();
 				temp =  $(this).val().split(":");
 				total = total + (parseFloat(temp[1]) * parseFloat(temp[2]));
				total = Math.round(total*Math.pow(10,2))/Math.pow(10,2);
				numberOfTickets += parseFloat(temp[2]);
 			}
 		});
 		if ($(this).val() != '') total = total + parseFloat($(this).val());
		total = Math.round(total*Math.pow(10,2))/Math.pow(10,2);
		var num_total	=	 parseFloat(total);
 		num_total		  = num_total.toFixed(2);
  	total = '$'+ num_total.toString();
  	$("#ticket_total").html(total); 
  });
  
  //pre-populating ticket options
  if($("#donation_info select").length >0){
  		var temp = new Array();
  		temp = $("#ticket_amount").val().split("|");
	
  		for(var i=0; i < (temp.length-1) ; i++){
	  		  sub_temp = temp[i].split(':');
	  		  var select_name = 'ticket_option_'+sub_temp[0];
		
	  		  $("#donation_info select").each(function(){
			 	 			if($(this).attr('id')== select_name){
			  		 		  temp[i]=temp[i].replace('_',' ');
			  		  		$('#' + select_name + ' option[value="' + temp[i] + '"]').attr('selected', 'selected');		  		  		
			  		  }
	  		  });	  		  
  		}
  		
  		//Calculating total amount of tickets & additional donation  
  		$("#donation_info select").change(function(){
		
  			var total= 0.0;
  			if($("#additional_donation").val() != ''){
	 				var total	= parseFloat($("#additional_donation").val());
	 			}
  			var selectedString	=	"";
  			var numberOfTickets = 0;	
  			 
	 			$("#donation_info select").each(function(){
		 				if($(this).val() != ''){
		 			  		selectedString =  selectedString + $(this).val()+'|';
			 					var temp = new Array();
			 					temp =  $(this).val().split(":");
			 					total = total + (parseFloat(temp[1]) * parseFloat(temp[2]));
								total = Math.round(total * Math.pow(10,2))/Math.pow(10,2);
								if((temp[3]) && (temp[3]!= "")){
									numberOfTickets += parseFloat(temp[2] * temp[3]);						//Calculate total number of seats based on tickets and seat count
		 						}else{
		 							numberOfTickets += parseFloat(temp[2]);	
		 						}
		 				}
	 			});
	 		
	 			$("#ticket_amount").val(selectedString);	
	 			var num_total	=	parseFloat(total);
	 			num_total			= num_total.toFixed(2);	
	    	total 				= num_total.toString();   	
	    	total 				= add_commas(total);
	    	$("#ticket_total").html('$'+total); 
	    	$("#ticket_total1").val(total);

 			
	 			//GENERATE NAME FIELDS
	 			var count = $(".buyer_name").length;
	 			if (numberOfTickets > count) {
	 				var qanda	= new Array();
	 				qanda = $('#complimentsstring').val().split("|");  //creating question answer list			
	 				//appending child node
	 				for (var i = 0;i <= (numberOfTickets - (count+1)); i++) {
	 						var index = count + i;	
	 						var qa_ol = '';
	 						if($('#complimentsstring').val()!=''){ 				
		 						qa_ol = '<li><ol>';						
				 				for (var j=0 ; j < (qanda.length) ; j++) {
				 					qa_ol +=	'<li><label for="buyer_compliments['+ index +']['+ j +']">'+qanda[j]+'*</label><input type="text" name="buyer_compliments['+ index +']['+ j +']" id="buyer_compliments['+ index +']['+ j +']" /></li>'
				 				}
				 				qa_ol +=	'</ol></li>';
			 				}
			 				$("#donation_info").append('<ul class="buyer_name"><li><label for="buyer_name['+index+']">Attendee Name '+(index+1)+'*</label><input type="text" name="buyer_name['+index+']" id="buyer_name['+index+']" value="" /></li>'+ qa_ol +'</ul>');
			  		}
			  	}
	
			  	if (count > numberOfTickets) {
			  		var tick = count-numberOfTickets;
	 				  for (var i = 1;i <= tick; i++) {
			  			$('.buyer_name:last').remove();
			  		}
			  	}
  		});
  }

  //event create: event type list item changed
  $('#type').change(function(){
   // alert($('#type').val());
    if($('#type').val()=='Design your Own'){
      $('#divcustomtype').show();
      $('#divsubtype').hide();
    }else{
      $('#divcustomtype').hide();
      $('#divsubtype').show();
	  Global.loadAction("#subtype", "GiveStaticData", {type: 'subcat', cat : $("#type").val(),subtype : $('#hidsubtype').val()});
      //var filename = MAIN_URL+escape("/give/GiveStaticData?type=subcat&cat=" + $('#type').val());
     // $("#subtype").load(filename);
    }
  });
    
  $('#duration').change(function(){
    if($('#duration').val()=='other'){
      $('#div_other_duration').show();
    }else{
      $('#div_other_duration').hide();

    }
  });


  $('a.cancelpayment').click(function(){
    var r=confirm("Are you sure you want to cancel your payment to SKC?");
    if(r==true){ 
      var filename = MAIN_URL_SSL + "/a/GiveCancelPayment?id="+this.id;
      $("#cancelfeedbackmsg").load(filename);    
    }
  });

  function addHiddenSubmit() {
	   var input = event.srcElement;
	   var elem = document.createElement("input");
	   elem.type = "hidden";
	   elem.name = input.name;
	   elem.value = input.value;
	   input.parentNode.appendChild(elem);
	}
	
	if(document.all) {
		$("input[type=image]").click(addHiddenSubmit);
	}
});


function add_commas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}