$(document).ready(function(){

  // apply pngFix
  $(document).pngFix();



  //add corners to the top nav elements;
  //$('#topnav>ul>li').corner('3px');

  //Trail search toggles
  $("label.custchkbox").click(function(){
    //first unset ALL hidden fileds in the form
    var thisHidField = $(this).attr('for') ;
    var oldVal = $('#'+thisHidField).val();
    if(oldVal==''){
      $('#'+thisHidField).attr('value','1')
      //set li class to 'on'
      $(this).parent().addClass('on');
    }else{
      $('#'+thisHidField).attr('value','')
      //set li class to ''
      $(this).parent().removeClass('on');
    }
    // Since an option was changed we MUST run a search now to get the Num Trails
    runSearch('true') ; //the true parame tells the fn to do a count only;

  });

    //Trail regions Dropdown;
    $('div.frm-selector>label').click(function(){
      $('#otherregions ul:open').slideUp('fast');
      $('#otherregions ul:hidden').slideDown('slow')

      //$('#otherregions ul').focus();
      //$('#otherregions ul').bind('blur',function(){alert('event fired');$(this).slideUp('fast')});
      return false;
    });

    $('document').click(function(){
      $('#otherregions ul:open').slideUp('fast');
    })

    //now set the hidden field with the value of this label
    $('#otherregions ul li a').click(function(){
      var sVal = $(this).html();
      var nVal = $(this).attr('rel');
      var sValUrlized = $(this).attr('title');
      //set region search value
      $('#hidregion').val(sValUrlized);
      $('#hidregionid').val(nVal);
      //set Region Search Label
      $('#hidregionlabel').html(sVal)
      //Close the selector
      $('#otherregions>ul').slideUp('fast');
      // a NEW region has been selected, run the search to count the trails
      runSearch('true')
      // end the click action
      return false;
    });

    $('#btn-getem').click(function(){
      runSearch('false');
      return false;
    });


    // Upload a Trail Photo
    $('#hpuploadsubmit, #btnpicupload').click(function(){

      var UploadForm = $('#upload-photo-form').html().replace('frmUploadPic','uploadPicFrm');
      //var UploadForm = $.get('/upload-photo/',{ajax:1},'','html') ;//('#upload-photo-form').html().replace('frmUploadPic','uploadPicFrm');

      $.prompt( UploadForm,
                { prefix: 'tb',
                  show: 'fadeIn',
                  promptspeed: 'slow' ,
                  buttons:{Cancel:false, Upload:true},
                  submit:badgeruploader
                }
              ).corner('8px');
      return false;
    });

// Join email list
  $('#hpemailaddress').focus(function(){
     if ($(this).val()=='your email address'){
       $(this).val('')
     }
  }).blur(function(){
     if ($(this).val()==''){
       $(this).val('your email address')
     }
  });

  // validate that it's an email address
  if ($("#hpsignupform").length) {
   $("#hpsignupform").validate();
  }



  // Trail Ratings Dropdown;
  $('div.frm-selector-sml>label').click(function(){
    //position the drop down relative to the label
    var moved = 0 ;
    if (moved<1) {
      var lblPos = $(this).position() ;
      var l = lblPos.left+'px';
      var t = (lblPos.top+1)+'px';
      $('#otherratings ul').css('left',l);
      $('#otherratings ul').css('top',t);
      moved = 1;
    }
    //$('#otherratings ul:open').slideUp('fast');
    $('#otherratings ul:hidden').slideDown('slow');
    return false;
  });

  // Trail Ratings Auto-Complete




  //now set the hidden field with the value of this label
  $('#otherratings ul li a').click(function(){
    var sVal = $(this).html();
    var nVal = $(this).attr('rel');
    //set rating search value
    $('#hidrating').val(nVal);
    //set Ratings Search Label
    $('#hidratinglabel').html(sVal)
    //Close the selector
    $('#otherratings>ul').slideUp('fast');
    return false;
  });


  if ($("#hptrailratename").length) {
    $("#hptrailratename").autocomplete('/ajax/trails.php', {
  		minChars: 3,
  		width: 180,
  		matchContains: true,
  		autoFill: false
  	});
  }


	$('#hptrailratename').focus(function(){
     if ($(this).val()=='trail name'){
       $(this).val('')
     }
  }).blur(function(){
     if ($(this).val()==''){
       $(this).val('trail name')
     }
  });



    //finally run the count on page load if it's the search page
    var myregexp = new RegExp('search') ;
    var myregexp2 = new RegExp('trails') ;
    var sUrl = window.location ;
    mymatch = myregexp.exec(sUrl);
    mymatch2 = myregexp2.exec(sUrl);
    if(mymatch=='search' || mymatch!=null || mymatch2=='trails' || mymatch2!=null) {
      runSearch('true')
    }

    /**
    * If someone tries to post a review on eth Rate a Trail page
    *  validate the Trail id / name name and comments
    **/
    $('#rateTrailSubmitButton').click(function(){
      var sErr = 'You Cannot rate a trail until you provide ALL the information<br />';
      var nErr = 0;
      if ($('#hptrailratename').val()=='' || $('#hptrailratename').val()=='trail name' ) {
        sErr+='<br />- tell us which trail. Start typing a trail name and select one from the list'
        nErr++;
      }

      if ($('#screen_name').val()==''  ) {
        sErr+='<br />- tell us your screen name';
        nErr++;
      }


      if ($('#email').val()==''  ) {
        sErr+='<br />- tell us your email address. Rest assured it will not be used for marketing purposes.';
        nErr++;
      }

      if ($('#review_text').val()=='') {
        sErr+='<br />- tell us what you think about this trail the Review section';
        nErr++;
      }

      if (nErr>=1) {
              $.prompt(sErr,{ prefix: 'tb',
                    show: 'fadeIn',
                    promptspeed: 'fast' });
        return false;
      }

    });

    /** add some corners to #centre-colum ul items**/
    $('#centre-column > ul,#centre-column > table > tbody > tr > td > ul ').corner('8px');

});



function runSearch(blCountOnly) {
  //get the values to build the url
  var sUrl = '/search' ;
  var sRegion = $('#hidregion').val();
  sUrl+='/region/'+sRegion ;

  // now the suitability options
  var aSuit = $('input.suitability[value=1]');
  var sSuitTypes = '';
  aSuit.each(function(){
   sSuitTypes+=$(this).attr('name')+',';
  });

  if (sSuitTypes!='') {
    //replace trailing comma
    sSuitTypes.replace('/(,$)/g','');
    var len = sSuitTypes.length;
    if (sSuitTypes.substr(len-1,1) == ",") {
        sSuitTypes = sSuitTypes.substring(0,len-1);
    }

    sUrl+='/features/'+sSuitTypes ;
  }

  if(blCountOnly=='true') {
    sUrl+='/countonly/true';
    $.getJSON(sUrl,function(oData){
      //extract the NumTrails and Populate it In the space provided in the search form
      nT = oData['num_trails'] ;
      $('#numtrails').html(nT);
    },'json');
    //do ajax lookup
  } else {
    //redirect to that url
    window.location = sUrl;
    return false;
  }
}


function badgeruploader(v,m,f) {

  if(!v){return;}

    if (v && f.copyright_confirmed=='Y' && f.trail!='') {
     $('#uploadPicFrm').submit();
    }else if(f.copyright_confirmed !='Y' ){
      $.prompt('You didn\'t tick the copyright box',{ prefix: 'tb',
                    show: 'fadeIn',
                    promptspeed: 'fast' });
    }

  return v;
}