
/*===============================================
JQuery Pagination.
===============================================*/
function pageselectCallback(page_index, jq){
	$('#Pagination').clone(true).appendTo('#Pagination1');
	
	var items_per_page = 10;
	
	if($(".story_result").length)
	{
		var num_entries = $('#hiddenresult div.story_result').length;
	}
	/*
	if($(".pg_wrap").length)
	{
		var num_entries = $("#hiddenresult div.pg_wrap").length;
	}
	*/
	var max_elem = Math.min((page_index+1) * items_per_page, num_entries);
	var new_content = '';
	
	if($(".story_result").length)
	{	
		for(var i=page_index*items_per_page;i<max_elem;i++)
		{
	  		new_content += $('div.story_result').eq(i).html();
		}
	}
	/*
	if($(".pg_wrap").length)
	{	
		for(var i=page_index*items_per_page;i<max_elem;i++)
		{
	  		new_content += $('div.pg_wrap').eq(i).html();
		}
	}
	*/
	
	$('#Searchresult').empty().append(new_content);
	
	$('#Pagination a').click(function(){
	  $('#Pagination1').empty();
	  $('#Pagination').clone(true).appendTo('#Pagination1');
	  $.scrollTo('#left_rail',{duration: 800, axis:"y"});
	});
	
	return false;
}

function initPagination() {
	if($(".story_result").length)
	{
 		var num_entries = $('#hiddenresult div.story_result').length;
	}
	/*
	if($(".pg_wrap").length)
	{
 		var num_entries = $('#hiddenresult div.pg_wrap').length;
	}
	*/
  	$("#Pagination").pagination(num_entries, {
    	items_per_page:10,
    	num_edge_entries: 2,
    	num_display_entries: 2,
    	callback: pageselectCallback
 	});
}

/*========================================================================
All GPI JQuery items are in this file
Written by David Shaner davidmshaner@yahoo.com
========================================================================*/

$(document).ready(function(){
  var myuser = $('#_userName').text();
  var myuserid = $('#_userLoggedIn').text();

  /*=============================================
  Add sectioncat to Saxotech search results
  =============================================*/
  if($(".saxotech_search_results").length){
    var sectioncat = window.location;
    var url='';
    sectioncat = String(sectioncat);
    var sectioncatloc = sectioncat.search(/Category=/);
    sectioncatloc = sectioncatloc + 9;
    sectioncat = sectioncat.substr(sectioncatloc, 3);

    $(".saxotech_search_results a").each(function(){
      url = $(this).attr("href");
      url = url + "?sectioncat="+sectioncat;
      $(this).attr("href", "");
      $(this).attr("href", url);
      url = '';
    });
  }


  if($('.correct_site').length){
    $('.pass_ret').clone(true).appendTo('.correct_site');
  }

  /*=============================================
  Display the login form
  =============================================*/
  $('.icon_login').click(function(){
     $(".login_form_holder").slideToggle("slow");
     $.scrollTo('#header_login',{duration: 800, axis:"y"});
     $('#email_field').focus().css('background-color','yellow');
     var redirect_url = window.location;
     $('#redirect_to').val(redirect_url);
  });

  if(myuserid > 0 ){
    $('.logout').show();
    $('.user_info').show();
    $('.icon_login').hide();
    $('.pass_ret').hide();
    $('#email_field').focus().css('background-color','#ffffff');
  }
  else{
    $('.icon_login').show();
    $('.logout').hide();
    $('.icon_register').show();
    $('#email_field').focus().css('background-color','yellow');
  }

   if($('#regfrm').length){
    $('.icon_login').hide();
  }

  /*=============================================
  Initiate the JQuery Pagination
  =============================================*/
  if($('#hiddenresult').length){
    initPagination();
  }

  /*=============================================
  Redirect to a new URL based on user selection
  This is used for Other GPI Websites in the
  header.
  =============================================*/
  if($('#myselect').length){
    $('#myselect').change(function(){
      var url = $(this).val();
      if(url.length){ window.open(url);}
    });
  }

  /*=============================================
  WPD redirect section 08
  =============================================*/
  if($('#wpd').length){
    $('#wpd').change(function(){
      var url = $(this).val();
      if(url.length){
	window.open(url);
      }
    });
  }
  /*=============================================
  Mimi redirect section 08
  =============================================*/
  if($('#mimi').length){
    $('#mimi').change(function(){
      var url = $(this).val();
      if(url.length){
	window.open(url);
      }
    });
  }
  /*=============================================
  Promo redirect section 08
  =============================================*/
  if($('#promo').length){
    $('#promo').change(function(){
      var url = $(this).val();
      if(url.length){
	window.open(url);
      }
    });
  }
  /*=============================================
  Gameredirect section 08
  =============================================*/
  if($('#game').length){
    $('#game').change(function(){
      var url = $(this).val();
      if(url.length){
	window.open(url);
      }
    });
  }
  /*=============================================
  OAC redirect section 08
  =============================================*/
  if($('#oac').length){
    $('#oac').change(function(){
      var url = $(this).val();
      if(url.length){
	window.open(url);
      }
    });
  }

  /*=============================================
  Accordion effect on the News Section Front.
  =============================================*/
  if($('#accordion').length){
    $("#accordion").accordion({
      header: 'h3',
      collapsible: true,
      active:false,
      autoHeight:false,
      clearStyle:true
    });
  }
  /*=============================================
  Photo Gallery Setup;
  =============================================*/
  if($(".gpi_image_gallery").length){

    $(".gpi_image_gallery_holder").hide();
    var cindex = '';
    var aindex = '';
    var url = window.location.host;

    $(".gpi_image_gallery").each(function(index){
      var myindex = $(this).index(".gpi_image_gallery");
      var image_link = $(".image_link").eq(myindex).text().replace(/&amp;/g, "&");
      var gallery_link = $(".gallery_link").eq(myindex).text().replace(/&amp;/g, "&");
      var photo_count = $(".photo_count").eq(myindex).text();
      var gal_description = $(".description").eq(myindex).text();
      var titles = $(".titles").eq(myindex).text();

      image_link = image_link.substr(0,image_link.length - 1);

      /* Create all the blank image galleries */
      $('<div class="simple_overlay" id="gallery'+myindex+'">').appendTo("#gallery_holder");
      $('<a class="prev"><</a>').appendTo("#gallery"+myindex);
      $('<a class="next">></a>').appendTo("#gallery"+myindex);
      $('<div class="info"></div>').appendTo("#gallery"+myindex);
      $('<img class="progress" src="/images/photo_gallery/loading.gif" />').appendTo("#gallery"+myindex);
      $('</div>').appendTo("#gallery"+myindex);

      /*Create the divs to hold the image links and captions*/
      $("<div id=\"triggers"+myindex+"\"></div>").appendTo(this);
      $("<div style=\"display:none\" class=\"captions\"></div>").appendTo(this);

      //add the picture urls
      for(i=1; i<=photo_count; i++){
	var caplink = gallery_link+"&Params=Itemnr="+i;
	$('<span></span>').appendTo(".captions").eq(myindex).load(caplink+' .mycaption','',function(){});

	if(i==1){
	  $('<div id="sum_img'+myindex+'" class="sum_img"><a id="'+myindex+'" class="pg" href="'+image_link+i+'&MaxH=500&MaxW=500"><img src="'+image_link+i+'&MaxW=100"/></a></div>').appendTo("#triggers"+myindex);
	  $('<div id="sum_text'+myindex+'" class="sum_text"><a id="'+myindex+'" class="ll" href="'+image_link+i+'&MaxH=500&MaxW=500">'+titles+'</a><p>'+gal_description+'<br/>'+photo_count+' photos.</p></div>').appendTo("#triggers"+myindex);
	  $('<div id="clear_left"></div>').appendTo("#triggers"+myindex);
	  $('<div class="article_separator"></div>').appendTo("#triggers"+myindex);

	}
	else{
	  $('<a style="display:none;" href="'+image_link+i+'&MaxH=500&MaxW=500"></a>').appendTo("#sum_img"+myindex);
	  $('<a style="display:none;" href="'+image_link+i+'&MaxH=500&MaxW=500"></a>').appendTo("#sum_text"+myindex);
	}
      } //end for i loop

    });

    $(window).load(function(){
    var ccaption ='';

      $(".captions").each(function(){
	var gindex = $(this).index(".captions");

	$(this).find("span.mycaption").each(function(index){

	  if($(this).text() == ""){
	    $(this).text("&nbsp");
	  }
	  $("#sum_img"+gindex).find("a").eq(index).attr("title",$(this).text());
	  $("#sum_text"+gindex).find("a").eq(index).attr("title",$(this).text());
	});
      });

      $("#Searchresult").hide();
      $(".gpi_image_gallery_holder").show();
    }); //end window.load function

    /*Click a photo gallery photo link */
    $(".pg").each(function(index){
      cindex = "#triggers"+$(this).attr("id");
      galindex = $(this).attr("id");
      $(cindex+" #sum_img"+galindex+" a").overlay({
	absolute: false,
	target: '#gallery'+galindex,
	expose: '#f1f1f1'
	}).gallery({
	  imgId:0,
	  speed: 800,
	  autohide: false,
	  template: '<strong>${title}</strong> <span>Image ${index} of ${total}</span>'
	});
    });

    /*Click a photo gallery photo link */
    $(".ll").each(function(index){
      aindex = "#triggers"+$(this).attr("id");
      agalindex = $(this).attr("id");
      $(aindex+" #sum_text"+agalindex+" a").overlay({
	absolute: false,
	target: '#gallery'+agalindex,
	expose: '#f1f1f1'
	}).gallery({
	  imgId:0,
	  speed: 800,
	  autohide: false,
	  template: '<strong>${title}</strong> <span>Image ${index} of ${total}</span>'
	});
    });
  } // end if statement

  /*=============================================
  Photo handler for Article Pages. Need the
  ability to handle multiple photos.
  Scroll and Overlay
  =============================================*/
  if($("div.scrollable").length){

    if($(".arphoto").length){
      $(".arphoto").each(function(index){
	var cutline = $(".arphoto .article_cutline").eq(index).text();
	if(cutline ==''){ cutline = "&nbsp;";}
	var copy = $(".arphoto .copy").eq(index).text();
	if(copy ==''){ copy = "&nbsp;";}
	else{
	  copy = "<br/><span class=\"photo_credit\" style=\"float:right; font-size:9px; font-weight:bold;\">Photo by: "+copy+"</span>";
	}
	var imgsrc = "http://"+window.location.host+$(".arphoto img").eq(index).attr("src");
	var image = "<div class=\"notcloned\"><a id=\""+index+"\" title=\""+cutline+"\" href=\""+imgsrc+"\" class=\"pg\">"+
		    "<img src=\""+imgsrc+"\" /></a><p>"+cutline+copy+"</p></div>";
	$(image).appendTo(".scrollable .items");
	//$(image).appendTo("#triggersag");
      });
    }
    else{
      $(".scrollable").css("display","none");
    }

    /* Extra Photos */
    if($(".exph").length){
      $(".exph").each(function(){
	var image = $(this).html();
	$(image).appendTo("#thumbnails .items");
      });
    }

    var n_photos = $(".items img").length;

    if(n_photos > 0){

    /* Resize the Thumbnail Images to Max 250W and Max 350D */
    $(".scrollable img").each(function() {
      var myphoto = $(this).attr('src');
      myphoto = myphoto.replace(/&/ig,"~");
      jQuery.getJSON("http://classified.gpubit.com/image_info1.php?q="+myphoto+"&callback=?",
      //jQuery.getJSON("http://classified.gpubit.com/image_info.php?z="+z+"&r="+actual_url+"&q="+myphoto+"&callback=?",

      function(data) {
	var width=''; var height='';
	width += data[2];
	height += data[3];
	myp_url = data[0];
	var zphoto = data[1]
	var maxWidth = 250;
	var maxHeight = 350;
	var ratio = 0;

	if(width > maxWidth){
	    ratio = maxWidth / width;
	    $(".scrollable img").eq(zphoto).attr("width", maxWidth);
	    $(".scrollable img").eq(zphoto).attr("height", height * ratio);
	    height = height * ratio;
	    width = width * ratio;
	}
	if(height > maxHeight){
	    ratio = maxHeight / height;
	    $(".scrollable img").eq(zphoto).attr("height", maxHeight);
	    $(".scrollable img").eq(zphoto).attr("width", width * ratio);
	    width = width * ratio;
	}

      });
      z++;
    });

    /* Setup the scrollable div to expand depending upon the image/cutline size */
   // var n_photos = $(".items img").length;
    var img_number = 1;
    var init_height = $(".scrollable .items div").eq(0).height();
    init_height = init_height + 25;

    $(".scrollable").css("height",init_height);

    if(n_photos > 1){
      $(".scrollable").append("<div class=\"w_images\"><a class=\"prevPage left\">Previous</a>"+
	"<span>Image "+img_number + " of " + n_photos +
	"</span><a class=\"right nextPage\">Next</a></div");
    }

    $("a.prevPage").click(function(){
      if(img_number === 1){ img_number = n_photos;}
      else{ img_number = img_number - 1;}

      var div_height = $(".scrollable .items div").eq(img_number).height();
      div_height = div_height + 25;

      $(".scrollable").css("height",div_height);
      $(".w_images span").empty();
      $(".w_images span").append("Image "+img_number + " of " + n_photos);
    });

    $("a.nextPage").click(function(){
      if(img_number === n_photos){ img_number = 1; }
      else{ img_number = img_number + 1; }

      var div_height = $(".scrollable .items div").eq(img_number).height();
      div_height = div_height + 25;

      $(".scrollable").css("height",div_height);
      $(".w_images span").empty();
      $(".w_images span").append("Image "+img_number + " of " + n_photos);
    });
	/*
    var pcredit = $('.photo_credit').html()
    if(pcredit ==''){ pcredit = "&nbsp;";}
    else{
      pcredit = "<br/>"+pcredit+"<br/>";
    }
	*/
	
	pcredit_array = new Array();
	
	$('.photo_credit').each(function(){
	
		var pcredit = $(this).html()
    	if(pcredit =='')
    	{ 
    		pcredit = " ";
    	}
    	else
    	{
      		pcredit = "<br/>"+pcredit+"<br/>";
    	}
		
		pcredit_array.push(pcredit);
	
	});

		$(".notcloned a").each(function(){
			var mytitle = $(this).attr("title");
			var myid = parseInt($(this).attr("id"));
			var aphoto_number = myid + 1; 
			$(this).attr("title",mytitle+pcredit_array[myid]+"<span>Image "+aphoto_number+" of "+n_photos+"</span>");
		});
	

    /* Thumbnail scrollable */
    ////////var images = $("div.scrollable").scrollable({size: 1, api:true});
    $("div.scrollable").scrollable({
      size: 1,
      clickable: false
    }).circular();

    $("#triggersag div[class!= notcloned cloned] a.pg").overlay({
      absolute: true,
      target: '#gallery1',
      expose: '#f1f1f1'
    }).gallery({
      speed: 800,
      autohide: false,
      //template: '<strong>${title}</strong>'+'<span>Image ${index} of '+n_photos+'</span>'
      template: '<strong>${title}</strong>'
    });
    } // end if statement for number of photos
  }
//'<strong>${title}</strong> <span>Image ${index} of ${total}</span>',${index}
  /*===============================================================================================
  Change the background color of the footer column on mouseover/mouseout
  ===============================================================================================*/
  if($('.footer_col').length){
    $('.footer_col').each(function(index){
      $(this).mouseenter(function(){
	$(this).css("background-image","url('/images/footer_bgnd_hover.gif')");
      });
      $(this).mouseleave(function(){
	$(this).css("background-image","url('/images/foot_col_bkg.png')");
	$(this).css("background-image","repeat-x");
      });
    });
  }

  //for the wide footer
   if($('#footer_col_wide').length){
    $('#footer_col_wide').each(function(index){
      $(this).mouseenter(function(){
	$(this).css("background-image","url('/images/footer_bgnd_hover_wide.gif')");
      });
      $(this).mouseleave(function(){
	$(this).css("background-image","url('/images/foot_col_bkg.png')");
	$(this).css("background-image","repeat-x");
      });
    });
  }

  /*===============================================================================================
  Increase/decrease font size on article pages
  ===============================================================================================*/
  if($('#story_container').length){
    $('#fontsizer').jfontsizer({
      applyTo: '#story_container',
      changesmall: '2',
      changelarge: '2',
      expire: -1
    });
  }

  /*===============================================================================================
  Show the classified search results
  ===============================================================================================*/
  function showResult(str){
    if (str.length==0 || str.length <= 2 ){
      document.getElementById("livesearch").innerHTML="";
      document.getElementById("livesearch").style.border="0px";
      return;
    }

    $.getJSON("http://classified.gpubit.com/livesearch.php?q="+str+"&callback=?",//ticker.php?callback=?",

    function(data) {
      var res = '';
      for(var i=0; i<data.length; i++) {
	res+= "<p>"+data[i].results + "</p>";
      }
      $("#livesearch").html(res);
    });
  }
  /*-------------------------------------------
  popup function for the video player
  -------------------------------------------*/
  if($('.popitup').length){
    $('.popitup').popupWindow({
      height:585,
      width:810,
      top:50,
      left:50
    });
  }
  if($('.termsofservice').length){
    $('.termsofservice').popupWindow({
      height:500,
      width:500,
      top:50,
      left:100,
      scrollbars:1
    });
  }
  /*===============================================================================================
  This is the addthis code. It will be prepended on to the font sizer area and append to the
  columnist_title_share_hold(Blogs and Columns)
  ===============================================================================================*/
  if($('.fsizer').length){
    $('#left_rail').append(
      '<script type="text/javascript">'+
      'var addthis_config = {'+
	'username: "editorial",'+
	'data_track_clickback: true'+
      '}'+
      '</script>');
    $('.fsizer').prepend(
      '<!-- AddThis Button BEGIN -->'+
     '<a href="http://www.addthis.com/bookmark.php?v=250&amp;username=editorial" class="addthis_button_compact"></a>'+
      '<a class="addthis_button_facebook"></a>'+
      '<a class="addthis_button_myspace"></a>'+
      '<a class="addthis_button_google"></a>'+
      '<a class="addthis_button_twitter"></a>'+
      '<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js"></script>'+
    '<!-- AddThis Button END -->'
    );
  }
  if($('#columnist_title_share_hold').length){
    $('#columnist_title_share_hold').append(
      '<!-- AddThis Button BEGIN -->'+
      '<a href="http://www.addthis.com/bookmark.php?v=250&amp;username=editorial" class="addthis_button_compact"></a>'+
      '<a class="addthis_button_facebook"></a>'+
      '<a class="addthis_button_myspace"></a>'+
      '<a class="addthis_button_google"></a>'+
      '<a class="addthis_button_twitter"></a>'+
      '<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js"></script>'+
      '<!-- AddThis Button END -->'
    );
  }
  /*===============================================================================================
  Close the individual accordion
  ===============================================================================================*/
  $('.close_accord').click(function(){
    var my_close = $(this).index('.close_accord');
    var accordion = $('h3.ui-accordion-header').eq(my_close);
    $(accordion).removeClass('ui-state-active');
    $(accordion).addClass('ui-state-default');
    $(accordion).attr('aria-expanded',false);
    $(accordion).attr('tab-index','-1');

    var icon = $('.ui-icon').eq(my_close);
    $(icon).removeClass('ui-icon-triangle-1-s');
    $(icon).addClass('ui-icon-triangle-1-e');

    var active = $('.ui-accordion-content').eq(my_close);
    $(active).attr('role','tab');
    $(active).attr('style','display:none');
    $(active).removeClass('.ui-accordion-content-active');
    $.scrollTo('#accordion',{duration: 800, axis:"y"});
  });

  /*=============================================
  The slider configuration.
  Photos need to be resized by calling a
  page on gpubit.
  =============================================*/
  if($('div.slide_image_holder').length){ //($('#news_slider').length){
    var z=0;
    $('div.slide_image_holder').find('img').each(function() {

	var actual_url = window.location.host;
	var myphoto = $(this).attr('src');
	myphoto = myphoto.replace(/&/ig,"~");
	jQuery.getJSON("http://classified.gpubit.com/image_info.php?z="+z+"&r="+actual_url+"&q="+myphoto+"&callback=?",

	function(data) {
	  var width=''; var height='';
	  width += data[2];
	  height += data[3];
	  myp_url = data[0];
	  var zphoto = data[1]
	  var maxWidth = 350;
	  var maxHeight = 250;
	  var ratio = 0;

	  if(width > maxWidth){
	      ratio = maxWidth / width;
	      $('div.slide_image_holder img').eq(zphoto).attr("width", maxWidth);
	      $('div.slide_image_holder img').eq(zphoto).attr("height", height * ratio);
	      height = height * ratio;
	      width = width * ratio;
	  }
	  if(height > maxHeight){
	      ratio = maxHeight / height;
	      $('div.slide_image_holder img').eq(zphoto).attr("height", maxHeight);
	      $('div.slide_image_holder img').eq(zphoto).attr("width", width * ratio);
	      width = width * ratio;
	  }

	});
	z++;
    });

    $('#news_slider').loopedSlider({
      container: '.container',
      slides: '.slides',
      pagination: '.navigation',
      containerClick: false,
      autoStart: 15000,
      restart: 10000,
      slidespeed: 1200,
      fadespeed: 300,
      autoHeight: false
    });
  }
});

