var default_search_text = 'Search All Requests';
var default_email_text = 'Add more text here if you would like';
$(document).ready( function(){

    // tab init
    var myRe2     = /\.com(\/.+)/;
    var myArray2  = myRe2.exec(document.URL);   // get just the *.html portion of the URL
    var url       = '';
    if(myArray2 != null)
    	url = myArray2[1]; 
    var myRe3     = /(poster|referer|referee|account)/;
    var myArray3  = myRe3.exec(url);
    if(myArray3 == null){
      $('#btnav a[@href='+url+']').parent().addClass('btnavhighlight');                    
    }
    else {
      $('#btnav a:nth(0)').parent().addClass('btnavhighlight');                          
    }
    $('#btleftnav a[@href='+url+']').parent().addClass('btleftnavhighlight');                    

    // for myTaskBar tabs
    $('#mytaskbar a').addClass('btmytasknorm'); 
    $('#mytaskbar a[@href='+url+']').removeClass('btmytasknorm');                    
    $('#mytaskbar a[@href='+url+']').addClass('btmytaskhover');                    
    $('#mytaskbar a').hover( 
                              function (){
                                $(this).removeClass('btmytasknorm');
                                $(this).addClass('btmytaskhover');
                              },
                              function (){
                                $(this).addClass('btmytasknorm');
                                $(this).removeClass('btmytaskhighlight');
                              });

    // background init
    var myRe     = /(php\/(account|poster|referer|referee)?)/;
    var myArray  = myRe.exec(document.URL);   // get just the *.html portion of the URL
    if (myArray!=null) {
    var location = myArray[1];

    if(location == 'php/'){
      $('#middle').addClass('greenback');
    } else {
      $('#middle').addClass('greyback');
    }
    }
    // for tabs
    $('.navtab').hover(
                       function() {
                         var tabname = $(this).attr('src');
                         var myRe = /(.+?)\.gif/; // get the text portion
                         var myArray = myRe.exec(tabname);
                         $(this).attr('src',myArray[1]+'-hover.gif');
                       },
                       function() {
                         var tabname = $(this).attr('src');
                         var myRe = /(.+?)-hover\.gif/; // get the text portion
                         var myArray = myRe.exec(tabname);
                         $(this).attr('src',myArray[1]+'.gif');
                       });


    // for poster/currentPostings
    $('.requestdetails').hide();
    $('.requestBtn').click( function() {
        var myid=$(this).attr('id');
	if($(this).html()=='[+]'){
	  $('.requestBtn').html('[+]');
	  $(this).html('[-]');
	  $('.requestdetails').hide();
	  $(this).parent().parent().find('.requestdetails').show();
          $('#referrals').load('/frontend_dev.php/poster/relatedEmails/id/'+myid);
	}
	else {
	  $(this).html('[+]');
	  $(this).parent().parent().find('.requestdetails').hide();
          $('#referrals').html('');
	}  
      } );
    $('.requestBtn:nth(0)').trigger('click');

    $('.postingEdit').click(
                           function() {
                             alert('Edit function not yet available');
                           });

    $('.postingComplete').click(
                           function() {
                             var postingId = $(this).attr('id');
                             var myRe = /comp-([\d]+)/; // get the numeric portion
                             var myArray = myRe.exec(postingId);
                             $('#referrals').html('<p>Loading...</p>');
                             $('#referrals').load('/frontend_dev.php/poster/completePosting/'+myArray[1],
                                                  function() {
                                                    initUpdatePosting();
                                                  });
                           });

    // for referer/currentReferrals
    $('.referraldetails').hide();
    $('.referralBtn').click( function() {
        var myid=$(this).attr('id');
	if($(this).html()=='[+]'){
	  $('.referralBtn').html('[+]');
	  $(this).html('[-]');
	  $('.referraldetails').hide();
	  $(this).parent().parent().find('.referraldetails').show();
          $('#referrals').load('/rrr/'+myid);
	}
	else {
	  $(this).html('[+]');
	  $(this).parent().parent().find('.referraldetails').hide();
          $('#referrals').html('');
	}  
      } );
    $('.referralBtn:nth(0)').trigger('click');


    $('.referralReport').click(
        function() {
          var postingId = $(this).attr('id');
          var myRe = /comp-([\d]+)/; // get the numeric portion
          var myArray = myRe.exec(postingId);
          $('#referrals').html('<p>Loading...</p>');
          $('#referrals').load('/crr/'+myArray[1],
               function() {
                   initUpdatePosting();
               });
        });


    // for referee/refereePosting
    $('#refemail').hide();
    $('#refreply').click( function(){

        if( $(this).attr('checked') == true ){
          $('#refemail').show();
        } else {
          $('#refemail').hide();
        }
      });
    $('#referToSomeoneElse').click( function() {
	window.location.href = $('#referToSomeoneElseLink').attr('href'); 
      });
    var service_type_value = $('#service_type').attr('value');
    if ($('#service_type').find('option[@value='+service_type_value+']').text() == 'Other'){
       $('#service_other').show();
    }
    else {
       $('#service_other').hide();
    }
    // for #referralform
    $('#service_list').hide();

    $('#location_box').hide();
    $('#other_location').click();
/*
    $('#best_describes').change( function(){

        if( $(this).attr('value') == '1' || $(this).attr('value') == '3' ){

          $('#service_list2').show();
        } else {
          $('#service_list').hide();
        }
    });

    if ($('#best_describes').attr('value')==1 || $('#best_describes').attr('value')==3) {
       $('#service_list').show();
    }
*/
   if ($("#category_type").val()=='') {
      makeSublist('best_describes','service_type', false, 0);
   }
   else {
      makeSublist('best_describes','service_type', false, $("#category_type").val());
    }
/*
    $('#other_location').click( function(){

        if( $(this).attr('value') == '0' ){
		  $('#location').val('');
          $('#location_box').hide();
        } else {
          $('#location_box').show();
        }
    });
*/
    $('#other_location_1_1').click( function(){
        if( $(this).attr('value') == '1' ){
          $('#location_box').show();
        } else {
          $('#location_box').hide();
        }
    });

    $('#service_type').change( function(){
	var value = $(this).attr('value');
        if( $(this).find('option[@value='+value+']').text() == 'Other' ){
          $('#service_other').show();
        } else {
          $('#service_other').hide();
        }
    });

    $('#referralform').submit( function() {
   if (get_reward_amount() < 5) 
     { 
         alert('$5 minimum required'); 
         return false; 
     }

	var value = $('#service_type').attr('value');
        if( $('#service_type').find('option[@value='+value+']').text() == 'Other' && $('#service_other_name').val()=='') {
             alert ("Please specify the service type.");
             return false;
         }

    if ((get_address()!='' || (get_location()!='' && get_location()!='Enter the location needed if different')) && get_item_value()!='' && get_item_value()!="Enter a title or heading of what you're looking for. Eg: A rent-controlled apartment" && get_find_by()!='' && get_reward()!='' && get_pay_when()!='' && get_pay_when()!="Please say when you'll consider this request 'closed'. Eg: 'When I sign the lease'" && get_extra_info()!='' && get_best_describes()!=0) {
      return true;
      //return confirm ("Post a request to find " + item + " by " + find_by + " for $" + (reward.toFixed(2)) + " when " + pay_when + "?");
   } else { 
      alert ("Please fill in the required fields.");
      return false;
   }

        var item = $('#item').attr('value');
        if( typeof(item) == 'undefined' ){
            alert('Please fill in the "I am looking for field');
            return false;
        }
        var reward = $('#reward').attr('value');
        if( typeof(reward) == 'undefined' || reward < 1){
            alert('Please fill in the "reward" field');
            return false;
        }
        if( $('#best_describes').attr('value') == '1' || $('#best_describes').attr('value') == '3' ){
          if( $('#service_type').attr('value') == 0 ) {
            $('#service_type').addClass('redbox');
            alert('Please indicate a category for the service you are look for or selling.');
            return false;
          }
        }
        return true;
      });


    // for all
    checkQ();
    $('#q').focus( function(){
        if($('#q').val() == default_search_text){
          $(this).val('');
        }
      });
    $('#q').blur( function(){
        checkQ();
      });
      
    // Email body text
    checkEmailText();
    $('#refbody').focus( function() {
      if($('#refbody').val() == default_email_text) {
        $(this).val('');
      }
    });
    $('#refbody').blur(checkEmailText);

    initUpdatePosting();
  });

function checkQ(){
  if($('#q').val() == ''){
    $('#q').val(default_search_text);
  }
}

function checkEmailText(){
  if($('#refbody').val() == '')
  {
    $('#refbody').val(default_email_text);
  }
}


function initUpdatePosting(){
    // for poster/posting
    $('#updatePostingStatus_1_1').click( function(){
          if($('#upra').attr('value')==1){
            $('#updatePostingReferees').show();
          } else {
            alert('Cannot mark successful (no referrals for this posting)');
            $(this).attr('value',0);
          }
      });
    $('#updatePostingStatus_2_2').click( function(){
          $('#updatePostingReferees').hide();
      });
    $('#updatePostingStatus').click( function(){
          $('#updatePostingReferees').hide();
      });


}


function backToRequests(){
   $('.referralBtn:nth(0)').trigger('click');
}

function recalculate_referer_reward()
{
    reward = get_reward_amount();
    rewardNum = Number(reward) * 0.8;
    rewardNum = rewardNum.toFixed(2);
    commission = Number(reward) - rewardNum;
    commission = commission.toFixed(2);  
    if ( reward >= 5 ) {
        $("#referer_reward").text("USD ($" + rewardNum + " will go to the Referer; $" + commission + " = ReferQuest's commission)");
    } else {
        $("#referer_reward").html("$5 minimum required");
    }
}

function get_reward_amount()
{
    reward = $("#reward").val();
    reward = reward.replace("$", "");
    reward = reward.replace(",", "");
    return Number(reward);
}

function truncate_words(limitField) 
{
   if (limitField.value.length > 65) {
        limitField.value = limitField.value.substring(0, 65);
   } 

}

function check_reward() {
    reward = get_reward_amount();
    if ( reward < 5 ) {
        alert("$5 minimum required");
        return false;
    }
    else if (isNaN(parseFloat(reward))) {
        alert("$5 minimum required");
        return false;
    }
    return true;
}

function preview_and_confirm_request()
{
    item = $("#item").val();
    find_by = $("#find_by").val();
    reward = $("#reward").val();;

    pay_when = $("#pay_when").val();
    best_describes = $("#best_describes").val();
    extra_info = $("#extra_info").val();
    if ( item && item!="Enter a title or heading of what you're looking for. Eg:A rent-controlled apartment" && find_by && reward && pay_when && pay_when!="Please say when you'll consider this request'closed.'Eg:'When i sign the lease'" && extra_info && best_describes!=0) {
      return confirm ("Post a request to find " + item + " by " + find_by + " for $" + (reward.toFixed(2)) + " when " + pay_when + "?");
   } else { 
      return false;
   }
}
//dropdownlist cascading from http://www.ajaxray.com/blog/2007/11/08/jquery-controlled-dependent-or-cascading-select-list-2/
 function makeSublist(parent,child,isSubselectOptional,childVal)
 {
 $("body").append("<select style='display:none' id='"+parent+child+"'></select>");
 $('#'+parent+child).html($("#"+child+" option"));
 var parentValue = $('#'+parent).attr('value');
 $('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
 childVal = (typeof childVal == "undefined")? "" : childVal ;

 $("#"+child+' option[@value="'+ childVal +'"]').attr('selected','selected');
 $('#'+parent).change( 
 function()
 {
 var parentValue = $('#'+parent).attr('value');
 $('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
 if(isSubselectOptional) 
 $('#'+child).prepend("<option value='none'> -- Select -- </option>");
 $('#'+child).trigger("change"); 
 $('#'+child).focus();
 }
 );
 }

/*
function makeSublist(parent,child,isSubselectOptional,childVal)
{
	$("body").append("<select style='display:none' id='"+parent+child+"'></select>");
	$('#'+parent+child).html($("#"+child+" option"));
	
		var parentValue = $('#'+parent).attr('value');
		$('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
	
	childVal = (typeof childVal == "undefined")? "" : childVal ;
	$("#"+child+' option[@value="'+ childVal +'"]').attr('selected','selected');
	
	$('#'+parent).change( 
		function()
		{
			var parentValue = $('#'+parent).attr('value');
			$('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
			if(isSubselectOptional) $('#'+child).prepend("<option value='none'> -- Select -- </option>");
			$('#'+child).trigger("change");
                        $('#'+child).focus();
		}
	);
}
*/

function get_item_value() {
   return $("#item").val();
}

function get_find_by() {
   return $("#find_by").val();
}

function get_reward() {
   return $("#reward").val()
}

function get_pay_when() {
   return $("#pay_when").val();
}

function get_best_describes() {
   return $("#best_describes").val();
}

function get_extra_info() {
   return $("#extra_info").val();
}

function get_address() {
   return $("#address").val();
}

function get_location() {
   return $("#location").val();
}

function postrequest() {
   if (get_reward_amount() < 5) 
     { 
         alert('$5 minimum required'); 
         return false; 
     }  else 
     {

    if ((get_address()!='' || (get_location()!='' && get_location()!='Enter the location needed if different')) && get_item_value()!='' && get_item_value()!="Enter a title or heading of what you're looking for. Eg:A rent-controlled apartment" && get_find_by()!='' && get_reward()!='' && get_pay_when()!='' && get_pay_when()!="Please say when you'll consider this request 'closed'. Eg: 'When I sign the lease'" && get_extra_info()!='' && get_best_describes()!=0) {
      //return true;
      return confirm ("Post a request to find " + item + " by " + find_by + " for $" + (reward.toFixed(2)) + " when " + pay_when + "?");
   } else { 
      return false;
   }
     }

}
function limitText(limitField, limitCount, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
        limitCount.value = limitNum - limitField.value.length;
    }
}
