var featuredCurrentId = 1;
function FeaturedNextPrev(selectedId, totalCnt, DivId, PagerId) {
  var j = featuredCurrentId;
  j = parseInt(selectedId);
        
  if (j > 0 && j < totalCnt + 1) {
    for (var i = 1; i <= totalCnt; i++) {
      if (document.getElementById(DivId + '-' + i)) {
        document.getElementById(DivId + '-' + i).style.display = 'none';
        document.getElementById(PagerId + '-' + i).className = '';
      }
    }

    if (document.getElementById(DivId + '-' + selectedId)) {
      document.getElementById(DivId + '-' + selectedId).style.display = 'block';
      document.getElementById(PagerId + '-' + selectedId).className = 'active';
    }
    featuredCurrentId = j;
  }

  var nextDiv = parseInt(selectedId) + 1;
  clearTimeout(timeOut);
  timeOut = setTimeout("autoplay_ticker("+nextDiv+", "+totalCnt+", 'homepageFeaturedDiv', 'homepageFeaturedPager')", 5000);
}

function blankcheck() {
  if(document.getElementById('email').value == "") {
    alert('Email can not be left blank');
    return false;
  }
  email = document.getElementById('email').value;

  if(!isValidEmail(email)) {
    alert('Please Insert Valid Email');
    return false;
  }

  if(document.getElementById('username').value == "") {
    alert('Name can not be left blank');
    return false;
  }
  
  if(document.getElementById('title').value == "") {
    alert('Title can not be left blank');
    return false;
  }

  if(document.getElementById('desc').value == "") {
    alert('Description can not be left blank');
    return false;
  }
}

function isValidEmail(email) {
    if (! allValidChars(email)) {  // check to make sure all characters are valid
       alert('Invalid email address.');
       return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
       alert('Invalid email address.');
       return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        alert('Invalid email address.');
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        alert('Invalid email address.');
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
        alert('Invalid email address.');
        return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
        alert('Invalid email address.');
        return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

function open_comment_box() {
  document.getElementById('comment_box').style.display = '';
}

var timeOut;
function autoplay_ticker(currentDiv, totalcnt, divid, pagerid) {
  if (currentDiv > totalcnt) { currentDiv = 1; }
  FeaturedNextPrev(currentDiv, totalcnt, divid, pagerid);
  var nextDiv = currentDiv + 1;
  clearTimeout(timeOut);
  timeOut = setTimeout("autoplay_ticker("+nextDiv+", "+totalcnt+", 'homepageFeaturedDiv', 'homepageFeaturedPager')", 5000);
}

function changeTab(tab) {
  document.getElementById('optionWeather').className = '';
  document.getElementById('optionCurrency').className = '';
  document.getElementById('optionTime').className = '';
  document.getElementById('optionAirport').className = '';
  document.getElementById('travel_tool_search').value = '';
  if(tab == 'weather') {
    document.getElementById('optionWeather').className = 'activetab';
    document.getElementById('optionImage').innerHTML = '<img alt="Weather" src="http://travel.hindustantimes.com/images/tt_pic.gif"/>';
    document.getElementById('optionText').innerHTML = 'To see the weather for many U.S. and world-wide cities, type "Weather" followed by the cities and state,U.S. Zip Code, or city and country.';
    document.getElementById('optionExample').innerHTML = 'e.g. Weather San Francisco';
  } else if(tab == 'currency') {
    document.getElementById('optionCurrency').className = 'activetab';
    document.getElementById('optionImage').innerHTML = '<img alt="Currency" src="http://travel.hindustantimes.com/images/finance.gif"/>';
    document.getElementById('optionText').innerHTML = 'To use our built-in currency converter, simply enter the conversion you’d like done into the Google search box and we’ll provide your answer directly on the results page.';
    document.getElementById('optionExample').innerHTML = 'e.g. 150 GBP in USD';
  } else if(tab == 'time') {
    document.getElementById('optionTime').className = 'activetab';
    document.getElementById('optionImage').innerHTML = '<img alt="Time" src="http://travel.hindustantimes.com/images/watch.gif"/>';
    document.getElementById('optionText').innerHTML = 'To see the time in many cities around the world, type in "time" and the name of the city. ';
    document.getElementById('optionExample').innerHTML = 'e.g. time London';
  } else if(tab == 'airport') {
    document.getElementById('optionAirport').className = 'activetab';
    document.getElementById('optionImage').innerHTML = '<img alt="Airport" src="http://travel.hindustantimes.com/images/airplane.gif"/>';
    document.getElementById('optionText').innerHTML = 'To see flight status for arriving and departing U.S. flights, type in the name of the airline and the flight number into the search box. You can also see delays at a specific airport by typing in the name of the city or three-letter airport code followed by the word "airport".';
    document.getElementById('optionExample').innerHTML = 'e.g. Houston airport';
  }
}

function openTraveloguesTab(openDiv) {
  document.getElementById('tabtraveloguesTab').className = '';
  document.getElementById('tabphotoTraveloguesTab').className = '';
  document.getElementById('tabreviewsTab').className = '';
  if(document.getElementById('tabtravelogues').style.display == '') {
    document.getElementById('tabtravelogues').style.display = 'none';
  }
  if(document.getElementById('tabphotoTravelogues').style.display == '') {
    document.getElementById('tabphotoTravelogues').style.display = 'none';
  }
  if(document.getElementById('tabreviews').style.display == '') {
    document.getElementById('tabreviews').style.display = 'none';
  }
  document.getElementById(openDiv+'Tab').className = 'active';
  document.getElementById(openDiv).style.display = '';
}

function popitup(url) {
  newwindow=window.open(url,'name','top=200,left=400,height=300,width=450');
  if (window.focus) {newwindow.focus()}
  return false;
}


function headerSearchForm(ht_blog_url) {
  var searchText = document.getElementById('searchTextBox');
 
  if (trim(searchText.value) === "") {
    alert("Please enter text to search.");
    searchText.focus();
    return false;
  }
  
  var url = ht_blog_url+'search.php';
  if (document.getElementById('searchRadioSite').checked) {
    url += '?search=' + searchText.value;
    url += '&IncludeBlogs=' + document.getElementById('searchIncludeBlogs').value;
    url += '&limit=5&searchType=site';
  }
  else {
    url += '?cx=005974345674175230622%3Adqxqvvndm0a&cof=FORID%3A10&ie=UTF-8&searchType=Google&sa=Search';
    url += '&q=' + searchText.value;
  }
  window.location.href = url;
}

function featuredSearch(ht_blog_url) {
  var searchText = document.getElementById('searchFeatured');
  if (trim(searchText.value) === "") {
    alert("Please enter text to search.");
    searchText.focus();
    return false;
  }
  
  var url = ht_blog_url+'search.php';
  url += '?search=' + searchText.value;
  url += '&IncludeBlogs=' + document.getElementById('searchIncludeBlog').value;
  url += '&limit=5&searchType=site';
  
  window.location.href = url;
}


// Removes starting whitespaces
function LTrim(value) {
  var re = /\s*((\S+\s*)*)/;
  return value.replace(re, "$1");  
}

// Removes ending whitespaces
function RTrim(value) {
  var re = /((\s*\S+)*)\s*/;
  return value.replace(re, "$1");  
}

// Removes leading and ending whitespaces
function trim(value) {  
  return LTrim(RTrim(value));  
}

function PaginationNextPrev(selectedId, totalCnt, DivId, PagerId) {
  var j = featuredCurrentId;
  j = parseInt(selectedId);
        
  if (j > 0 && j < totalCnt + 1) {
    for (var i = 1; i <= totalCnt; i++) {
      if (document.getElementById(DivId + '-' + i)) {
        document.getElementById(DivId + '-' + i).style.display = 'none';
        document.getElementById(PagerId + '-' + i).className = '';
      }
    }

    if (document.getElementById(DivId + '-' + selectedId)) {
      document.getElementById(DivId + '-' + selectedId).style.display = 'block';
      document.getElementById(PagerId + '-' + selectedId).className = 'active';
    }
    featuredCurrentId = j;
  }
}

function hide_commentbox() {
  document.getElementById('comment_box').style.display = 'none';
}

function save_entry_viewed_count(entry_id, entry_title, entry_url, ugcfolderpath) {
  jQuery.ajax({
        type: "POST",
        url: ugcfolderpath+"most_viewed_entry.php",
        data: "entry_id="+entry_id+"&entry_title="+entry_title+"&entry_url="+entry_url+"&action=save_count",
        success: function(responseData) {
          return true;
        }
      });
}

function get_most_viewed_entry(total_entry, ugcfolderpath) {
  jQuery.ajax({
        type: "POST",
        url: ugcfolderpath+"most_viewed_entry.php",
        data: "total_entry="+total_entry+"&action=get_most_read",
        success: function(responseData) {
           jQuery('#most_read_entry').html(responseData);
        }
      });
  document.getElementById('most_read').className = "active";
  document.getElementById('top_rated').className = "";
}

function get_top_rated_entry(total_entry, ugcfolderpath) {
  jQuery.ajax({
        type: "POST",
        url: ugcfolderpath+"most_viewed_entry.php",
        data: "total_entry="+total_entry+"&action=get_top_rated",
        success: function(responseData) {
           jQuery('#most_read_entry').html(responseData);
        }
      });
  document.getElementById('top_rated').className = "active";
  document.getElementById('most_read').className = "";
}

// function save_entry_viewed_count(entry_id, entry_title, entry_url) {
//   var pars; var url;
//   url = "http://202.54.157.212/httravel/htcode/ugc/most_viewed_entry.php";
//   pars = "entry_id="+entry_id+"&entry_title="+entry_title+"&entry_url="+entry_url+"&action=save_count";
//   new ajax(url, {postBody: pars, onComplete: save_entry_count_response});
// }
// 
// function save_entry_count_response(request) {
//   var result = request.responseText;
//   return true;
// }
// 
// function get_most_viewed_entry(total_entry) {
//   var pars; var url;
//   url = "http://202.54.157.212/httravel/htcode/ugc/most_viewed_entry.php";
//   pars = "total_entry="+total_entry+"&action=get_most_read";
//   new ajax(url, {postBody: pars, onComplete: get_entry_response});
// }
// 
// function get_entry_response(request) {
//   var result = request.responseText;
//   document.getElementById('most_read_entry').innerHTML = result;
//   return true;
// }

function stop_ticker(button_type, totalCnt) {
  if(button_type == 'play_img') {
    document.getElementById('play_pause').innerHTML = '<img onclick="stop_ticker(\'pause_img\', '+totalCnt+')" style="float:right; margin-left:5px;" src="http://travel.hindustantimes.com/images/play.jpg" alt="play" title="Play" />';
    clearTimeout(timeOut);
  } else {
    document.getElementById('play_pause').innerHTML = '<img onclick="stop_ticker(\'play_img\', '+totalCnt+')" style="float:right; margin-left:5px;" src="http://travel.hindustantimes.com/images/pause.jpg" alt="pause" title="Pause" />';
    nextDiv = parseInt(featuredCurrentId)+1;
    timeOut = setTimeout("autoplay_ticker("+nextDiv+", "+totalCnt+", 'homepageFeaturedDiv', 'homepageFeaturedPager')", 10);
  }
}

function KeyDownHandlerOfGenericSearch(event, btn, searchurl)
{    
  if (!(document.all && document.getElementById))
  {        
    if (event.which == 13)             
    {        
      // cancel the default submit
      event.returnValue=false;
      event.cancel = true;
      // submit the form by programmatically clicking the specified button            
      //btn.click();            
      headerSearchForm(searchurl);
    }
  }
  else
  {        
    if (event.keyCode == 13)             
    {        
    // cancel the default submit
    event.returnValue=false;
    event.cancel = true;
    // submit the form by programmatically clicking the specified button            
    //btn.click();
    headerSearchForm(searchurl);
    }
  }
} 

function counterUpdate(opt_countedTextBox, opt_countBody, opt_maxSize) {
  var countedTextBox = opt_countedTextBox ? opt_countedTextBox : "counttxt";
  var countBody = opt_countBody ? opt_countBody : "countBody";
  var maxSize = opt_maxSize ? opt_maxSize : 1024;

  var field = document.getElementById(countedTextBox);

  if (field && field.value.length >= maxSize) {
          alert("You Can't Enter More Than 500 chars.");
          field.value = field.value.substring(0, maxSize);
  }
  var txtField = document.getElementById(countBody);
          if (txtField) { 
          txtField.innerHTML = field.value.length;
  }
}

function verify_values() {
  if(document.getElementById('comment-author').value == "") {
    alert('Name can not be left blank');
    return false;
  }

  if(document.getElementById('comment-email').value == "") {
    alert('Email can not be left blank');
    return false;
  }
  email = document.getElementById('comment-email').value;

  if(!isValidEmail(email)) {
    alert('Please Insert valid email');
    return false;
  }

  if(document.getElementById('comment-text').value == "") {
    alert('Please enter text in comment box');
    return false;
  }

  if(!document.getElementById('agree_terms').checked) {
    alert('Accept the terms and condition before submitting comment');
    return false;
  }
  return true;
}

function close_alert() {
  document.getElementById('success_alert').style.display = 'none';
}

function play_selected_video(video_path, file_name) {
  var swf_name = file_name;
  document.getElementById('play_demo_video').innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="90%" height="700" id="'+swf_name+'" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="wmode" value="transparent" /><param name="movie" value="'+video_path+'/video_demo/'+swf_name+'.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#f5f5f5" /><embed src="'+video_path+'/video_demo/'+swf_name+'.swf" wmode="transparent" quality="high" bgcolor="#f5f5f5" width="90%" height="700" name="'+swf_name+'" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
}