//Opening hours Tabs Javascript
function openingHoursBuilder(){
	hideOHTabs();
	$('.tabLinkOH:first').click();
}
function hideOHTabs(){
	$('.tabLinkOH').each(function(){
		$(this).removeClass('selected');
		$($(this).attr("hash")).hide();
	});
}
function changeOHTab(tabLinkObj){
	hideOHTabs();
	tabLinkObj.addClass('selected');
	$(tabLinkObj.attr("hash")).show();
}
$('.tabLinkOH').live("click", function(){
	changeOHTab($(this))
	return false;
});
$('.miCapture').live('click', function () {
  var currNatID = $(this).closest('.parentListing').attr('data-natid');
  GB_show('/micapture/AddContentAction.do?natid=' + currNatID, 560, 800, 'iframe');
  return false;
});
$('.menu').live('click', function () {
  var currNatID = $(this).closest('.parentListing').attr('data-natid');
  var menuPageUrl = '/ucs/MenuPageAction.do?natid=' + currNatID +'&page=1';
  if(page == "lightbox"){
    parent.window.GB_show(menuPageUrl, 560, 800, 'iframe');
  }else{
  GB_show(menuPageUrl, 560, 800, 'iframe');
  }
  return false;
});
$(function(){
  openingHoursBuilder();
	//Make tabs and tab nav highlighting work	
	$('.tab-section').each(function(item){
		var tabSectionID = $(this).attr('id');
		$('#'+tabSectionID+' .tab-nav li').click(function(){
			$(this).siblings().removeClass('selected').end().addClass('selected');	
			targetDiv = $(this).children('a').attr('href');
			$(this).parent().siblings('.tab').hide();
			$(targetDiv).show();
			if(targetDiv.indexOf('#call-for-free')!=-1){
				if($(targetDiv+' iframe').attr('src')=='http://www.yell.com/yell/loading.html'){
					iUrl = $(targetDiv+' iframe').attr('data-cffurl');
					$(targetDiv+' iframe').attr('src',iUrl);
				}
			}		
			$('#y-fullwidthContainer').hide().show();	
			return false;
		}).eq(0).addClass('selected');
		$('#'+tabSectionID+' .tab').hide().eq(0).show();
	});
	
	//Validation for email business form
	
	$('.email-business textarea').live('keyup',function(){
		var content = $(this).val();
		maxlength = 2000;
		if($(this).next().hasClass('error')){
			$(this).next().remove();
		}
			
		if(content.length<maxlength){
			$(this).next().html("<strong>"+eval(maxlength-content.length)+"</strong> characters remaining");
		}else{
			$(this).val(content.substring(0,maxlength));
			$(this).next().html("<strong>Maximum message length reached</strong>");	
		}
	}).keyup();
	
	$('.send-email').live('click',function(){

		//Collect form values
		var natID = $(this).closest('form').attr('id').replace('email-business-form-','');	
		var natToSend = $('#natid-'+natID).val();
		var adIdToSend = $('#uniqueAdID-'+natID).val();
		var $subject = $('#subject-'+natID);
		var $email = $('#sender-'+natID);
		var $message = $('#text-'+natID);
		var emailPattern = /^([a-z0-9_\'.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
		
		var pass = true;
		
		$('#email-business-'+natID+' .error').remove();
		//validate subject
		if($subject.val()==''){
			pass = false;
			$subject.after('<p class="error">You must include a subject for your message</p>');
		}
		
		//validate email address
		if($email.val()==''){
			pass = false;
			$email.after('<p class="error">You must include an email address</p>');
		}else if(!emailPattern.test($email.val())){
			pass = false;
			$email.after('<p class="error">You must include a valid email address</p>');
   		}  
			
   		
   		//validate message
   		if($message.val()==''){
	   		pass = false;
 			$message.after('<p class="error">You must include a message</p>');
  		}		
  		
  		if(pass){
			var dataString = 'natid='+natToSend+'&uniqueAdID='+ adIdToSend +'&subject='+ $subject.val() + '&sender=' + $email.val() + '&text=' + $message.val().replace(/%/g,"%25");  
			$.ajax({  
			  	type: "POST",  
			  	url: "/mel/simple",  
			  	data: dataString,  
			  	dataType: "string",
			  	success: function(xml) {  
					if(xml.indexOf('<email result="sent">')!=-1){
						$('#email-business-form-'+natID).hide().after("<p class='success-message'>Your message has been sent successfully.</p>");
				  	}else{
					 	$('#email-business-form-'+natID).append("<p class='error'>There has been a problem sending your message, please try again later.</p>");
					}
				}  
			});  
  		}
  		$('body').hide().show(); //nasty fix for page redraw bug in IE8
		return false;
	});

  /**
  * Map & directions
  */
  
  //Validation for directions form

  // submit event
  $('.parentListing').delegate('.capsuleDirections', 'submit', function() {
    var $capsule = $(this).closest('.map-and-directions-tab');
    var $capsuleDirectionsForm = $capsule.find('form.capsuleDirections');
    var $directionsInput = $capsuleDirectionsForm.find('input[name=route1]');
    var travelType = $capsuleDirectionsForm.find('input[name=traveltype]').val().toUpperCase();
      if ($directionsInput.val() != '' && $directionsInput.val() != $directionsInput.attr('placeholder')) {
        s.events = '';
        s.tl(this,'o','TAB:MAPS:MAP:DIRECTIONS:'+travelType);
        $capsuleDirectionsForm.find('.directions-error-message').hide();
        return true;
      }
      else {
        $capsuleDirectionsForm.find('.directions-error-message').show();
        return false;
      }
  });
  // toggle route type event
  $('.parentListing').delegate('.routeTransportToggle', 'click', function() {
    $travelType = $(this).parent('form').find('input[name=traveltype]');
    if ($(this).hasClass('driving')) {
      $(this).removeClass('driving').addClass('walking');
      $travelType.val('walking');
    } else {
      $(this).removeClass('walking').addClass('driving');
      $travelType.val('driving');
    }
  });
  $('.parentListing').delegate('a.mmb', 'click', function() {
    s.events = '';
    s.tl(this,'o','TAB:MAPS:MAP:MMB');
    parent.window.GB_show($(this).attr('href'), 560, 800, 'iframe');
    return false;
  });
  
  
  if($('.streamCount').size() >= 1){
    videoViewCount();
  }
});
// Remove Omniture onclick events from VML elements in IE, as they produce Javascript errors
function removeVmlEvents() {
	removeClickEventsFrom('rect');
	removeClickEventsFrom('stroke');
	removeClickEventsFrom('fill');
	removeClickEventsFrom('oval');
	removeClickEventsFrom('polyline');
	removeClickEventsFrom('shape');
}
function removeClickEventsFrom(selector) {
	var elements = $(selector);
	for (var index = 0; index < elements.length; index++) {
		var element = elements[index];
		if (element.detachEvent && !element.onclick && s && s.bc) {
			element.detachEvent('onclick', s.bc);
			element.onclick = cancelAction;
		}
	}
}

function viewCountPost(curObj, streamname) {
    if (curObj.currentTime == 0 || curObj.currentTime == curObj.duration) {
       $.ajax({
        type: 'POST',
        url: '/video/VideoPlayCount?streamname='+streamname,
        success: function(data) {
            for(stream in data){
              //do nothing
            }
          }
      });
    } 
}

function videoViewCount(){
  var pageStreams = [], vidStreamsUrl;
  $('.streamCount').each(function(index, element){
      var thisStream = element.id.slice(7);
      pageStreams.push(thisStream);
  });
  for (i = 0; i < pageStreams.length; i += 1) {
    if(i===0){vidStreamsUrl = '?'}

    vidStreamsUrl += 'streamname='+pageStreams[i];
    if(i != pageStreams.length){vidStreamsUrl += '&'}
  }
  if(vidStreamsUrl){
    $.ajax({
      url: '/video/VideoPlayCount'+vidStreamsUrl,
      success: function(data) {
        for(stream in data){
          $('#stream_'+stream).html(data[stream].playcount+' views<span class="pipeSpacer">|</span> ').show();
        }
      }
    });
  }
}
