// JavaScript Document
var voted = 0;
var filter_using = 0;
$(function(){
  //create lighbox elements
  $('.pbi_images a').lightBox({
	overlayBgColor: '#000',
	overlayOpacity: 0.6,
	imageLoading: '/bibivu/tpl/js/lightbox/images/lightbox-ico-loading.gif',
	imageBtnClose: '/bibivu/tpl/js/lightbox/images/lightbox-btn-close.gif',
	imageBtnPrev: '/bibivu/tpl/js/lightbox/images/lightbox-btn-prev.gif',
	imageBtnNext: '/bibivu/tpl/js/lightbox/images/lightbox-btn-next.gif',
	imageBlank: '/bibivu/tpl/js/lightbox/images/lightbox-blank.gif',
	containerResizeSpeed: 350,
	txtImage: 'PBIDir - ',
	txtOf: 'of'
  });

  //toggle rows in a table
  $('.tab_head').click(function() {
    $('.tab_body_' + $(this).attr('id').substring(9)).toggle();
  });

  //tabbing on the pbi page
  $('.pbi_releases > ul').tabs();
  
  //images scroller for pbi page
//  imageScroller("viewerFrame");

  // Document is ready
  imgLoader = new Image();// preload image
  imgLoader.src = pathToLoadImage;
  $(document).ajaxStart(function(){
	$("body").append("<div id='divBox_load'><img src='"+imgLoader.src+"' /></div>");
	$('#divBox_load').show();
  });

  $(document).ajaxStop(function(){
	divBox();
	$('#divBox_load').hide().trigger("unload").unbind().remove();
  });

  init();
});
function init(){
  divBox();
  
  $('table.sortable thead tr th').click(function() { 
	  filter_using = this.column + 1;
  }); 

//  $('table.sortable tbody tr:not([th]):odd').removeClass('row_even').addClass('row_odd');
//  $('table.sortable tbody tr:not([th]):even').removeClass('row_odd').addClass('row_even');
  $('table.sortable tbody tr:not([th])').hover(
											   function() { $(this).addClass("row_hover"); },
											   function() { $(this).removeClass("row_hover"); }
											   ).click(
											   		   function(){$(this).toggleClass("row_highlight"); }
											   		   );
  $('#filter').bind('change',
					function(){
						if($('#filter').val()==''){
							$('table.sortable tbody tr').show();
						} else {
							$('table.sortable tbody tr').each(function() {
																	  if ($('td:nth-child('+filter_using+')', this).text().toLowerCase().indexOf($('#filter').val().toLowerCase())>=0) {
																		  $(this).show();
																	  } else if ($('th',this).length == 0){
																		  $(this).hide();
																	  } else {
																		  $(this).hide;
																	  }
																	});
						};
					});
}
function mailprotect (user, domain, ext, name) {
	document.write("<" + "a" + " hr" + "ef=" + "mai" + "lto:" + user + "@" + domain + "." + ext + ">" + name + "</" + "a>");
}

function updateVote(tvote) {
	if(voted<=0){
		if(tvote<=0 && voted>0){
			tvote = voted;
		}
		$('.vote_vote').removeClass('vote_selected').removeClass('vote_selected_back');
		if(tvote>0){
			$('#vote_10 a').html(tvote + "");
			$('#vote_' + tvote).addClass('vote_selected');
			for(i=1;i<=tvote;i++){
				$('#vote_' + i).addClass('vote_selected_back');
			}
		} else {
			$('#vote_10 a').html("");
		}
	}
}

function saveVote(pbi_id,tvote){
	if(voted<=0 && tvote>0){
		$.post("/bt/pbi/" + pbi_id + "/vote/"+ tvote,
			{ajax:1},
			function(data,textStatus){
				if(textStatus=='success'){
					if(data == 'success' || data>0){
						voted=tvote;
						no_more_votes();
						if(data>0){
							$('.rating_bar').html(data).width(data*10);
						}
						alert ('Thank you for your vote !');
					} else {
						alert ('Error: ' + data);
					}
				} else {
					alert ('Error casting your vote!!' + "\n\n" + textStatus);
				}
			});
	} else if(voted>0){
		no_more_votes();
	}
}

function no_more_votes(){
	if(voted>0){
		var tvote = $('#vote_10 a').html();
		$('.vote_vote').html("&nbsp;");
		$('#vote_10').html(tvote);
	}
}

/*******************************************
 *  COMMENTS
 ******************************************/
function check_comment_submit(){
	var pbi_comment = jQuery.trim($('#pbi_comment').val());
	if(pbi_comment==''){
		alert('You must enter a comment !!');
		return false;
	}
	return true;
}

function load_comment_form(form_uri){
	$('#comment_form_div').load(form_uri,
		function(){
			$('#pbi_comment').focus();
		});
}


function saveComment(save_comment_uri){
	if(check_comment_submit()){
		$.post(
			save_comment_uri,
			{
				pbi_comment: $.trim($('#pbi_comment').val()),
				ajax:1
			},
			function(xml){
				var _error = '';
				var _date = '';
				var _user = '';
				var _body = '';
				$("message",xml).each(function(){
					_error	= $('error',this).text();
					if(_error==''){
						_cid	= $('cid',this).text();
						_date	= $('date',this).text();
						_user	= $('user',this).text();
						_body	= $('body',this).text().replace(/\n/g, '<br />');
						_usr_uri= $('usr_uri',this).text();
						prependComment(_cid, _user, _date, _body, _usr_uri);
						$('#comment_form_div').html("");
					} else {
						alert ('Error Saving your comment!!' + "\n\n" + _error);
						return false;
					}
				})
			}
		);
		return false;	//using ajax !!! - set this to TRUE if want to post the form via BROWSER POST, remove the "$.post" as well
	} else {
		return false;
	}
}

/*******************************************
 * create a new comment
 ******************************************/
function showComment(cid, user, date, comment, user_uri){
	var newMSG = '';
	newMSG = newMSG + '<div class="comment_message" id="cid' + cid + '"><div class="comment_header">';
	newMSG = newMSG + '<span class="comment_user"><a href="' + user_uri + '" target="_top">' + user + '</a></span>';
	if(can_comment_delete){
		newMSG = newMSG + '<span class="comment_actions"><a href="javascript:void(0);" onclick="deleteComment(' + cid + ');" target="_top">delete #' + cid + '</a></span>';
	}
	newMSG = newMSG + '<span class="comment_date">' + date + '</span>';
	newMSG = newMSG + '</div>';
	newMSG = newMSG + '<div class="comment_body">' + comment + '</div>';
	newMSG = newMSG + '</div>';
	return newMSG;
}

function deleteComment(cid){
	if(cid!=''){
		if(confirm('Are you sure you want to remove Comment #' + cid)){
			$.get(delete_comment_uri + "/" + cid,
				function(data,textStatus){
					if(textStatus=='success'){
						if(data == 'success'){
							$('#cid' + cid).trigger("unload").unbind().remove();
						} else {
							alert ('Error: ' + data);
						}
					} else {
						alert ('Error deleting the comment!!' + "\n\n" + textStatus);
					}
				});
		}
	}
}

function appendComment(cid, user, date, comment, user_uri){
	$('#comment_list').append(showComment(cid, user, date, comment, user_uri));
}

function prependComment(cid, user, date, comment, user_uri){
	$('#comment_list').prepend(showComment(cid, user, date, comment, user_uri));
}

/*******************************************
 * subscription
 ******************************************/
function subscribe_pbi(uri){
	$.get(
		uri,
		function(data,textStatus){
			if(textStatus=='success'){
				$('#subscribe_pbi').html(data);
			} else {
				alert ('Error updating subscription!!' + "\n\n" + textStatus);
			}
		}
	);
	return false;
}
/*******************************************
 * manage Forms via XML
 ******************************************/
function postForm(form,uri, message_success){
	var message_success = (message_success == null) ? false : message_success;
	var ok = false;
	if(uri.indexOf('delete')>=0){
		ok=confirm('You sure you want to continue ?');
	} else {
		ok=true;
	}
	if(!ok) return false;
	var values = {'ajax':''};
	var sel = {};
	var getValue = (function(what, tt){
		var nn = $(what).attr("name");
		var vv = $(what).val();
		values[nn] = vv;
		if(tt == 'select')	sel[nn] = $('#'+nn+vv,what).text();
		else				sel[nn] = null;
	});
	$('.' + form + ' input').each(function(){getValue(this, 'input');});
	$('.' + form + ' select').each(function(){getValue(this,'select');});
	$('.' + form + ' textarea').each(function(){getValue(this,'textarea');});
	$.post(
		uri,
		values,
		function(data){
			if(data=='success'){
				if(message_success==true){
					alert('Action Successfully Completed !!');
				}
				//need to update the table ROW as well
				divBox_remove();
				if(values['id']<=0){
					//need to refresh the page
					window.location.reload();
				} else if(uri.indexOf('delete')>=0){
					$('#rec' + values['id']).trigger("unload").unbind().remove();
				} else {
					for (var key in values){
						var txt = $('#' + key + '_' + values['id']).html();
						if(null != txt){
							vv = null==sel[key]?values[key]:sel[key];
							if(txt.indexOf("<a")>=0){
								$('#' + key + '_' + values['id'] + ' a').text(vv);
							} else if(txt.indexOf("<img")>=0){
								$('#' + key + '_' + values['id'] + ' img').attr('src',vv);
							} else {
								$('#' + key + '_' + values['id']).text(vv);
							}
						}
					}
				}
			} else {
				alert('Error!!' + "\n\n" + data);
			}
		}
	);
	return false;
}


function show_related_table(uri, field_to, field_from, div, click_from){
	var t = {};
	t[field_to] = field_from;
	t["_srt_field_to"] = field_to;
	t["_srt_field_from"] = field_from;
	t["_srt_div"] = div;
	t["ajax"] = '1';
	if(click_from!=''){
		$(click_from).html($(click_from).html().replace(/show|refresh/i,'Loading') + '...');
	}
	$.post(uri,t, function(data){
						   $('#'+div).html(data);
						   init();
						   if(click_from!=''){
							   $(click_from).html($(click_from).html().replace(/Loading/i,'Refresh').replace(/\.\.\./,''));
						   }
						});
}

/*******************************************
 * show a new DIV with content
 ******************************************/
function divBox(){
	$('.divBox').click(function(){
								if(this.tagName.toLowerCase()=='a'){
									divBox_open($(this).attr('href'));
//								} else if($(this).parent().tagName.toLowerCase()=='a') {
								} else {
									divBox_open($(this).parent().attr('href'));
								}
								return false;
								}).removeClass('divBox');
}
function divBox_open(uri){
	//I did not like some functionalities of thickbox
	//so here is my solution
	//create a new div as large as the .content div
	//starting to the same TOP and LEFT of .content
	//and pretty much emulate the thickbox
	if(uri=="") return false;
	divBox_remove();
	var divName = 'FP_divBOX';
	var ddiv = $( "<div id='"+divName+"'><br /></div>" );
	ddiv.load(uri);
	var orig = $('#content');
	var offset = orig.offset();
	var oWidth = orig.width();
	var oHeight = orig.height();

	var t = orig;
	while(oWidth == 0){
		t = t.parent();
		oWidth = t.width();
	}
    orig.after(ddiv);
	ddiv.show();
	orig.hide();
}
function divBox_remove(){
	var divName = 'FP_divBOX';
	var orig = $('#content');
	$('#' + divName).hide().trigger("unload").unbind().remove();
	orig.show();
}


function imageScroller(frame){
	var _imgFrame = $('.' + frame);
	var _child = "a";
	var _itv;
	var imgScroller = function(){
		autoStop();
		_imgFrame.find(_child+":first").clone().show().appendTo( _imgFrame );
//		_h = $('img',_imgFrame.find(_child+":first")).height()
		$('img',_imgFrame.find(_child+":first")).animate({height:0},'slow', function(){
			_imgFrame.find(_child+":first").remove().hide();
			autoPlay(); 
		});
																								   
		
//		_imgFrame.animate( {marginTop:-_h}, 'slow' ,'', function(){
//			_imgFrame.find(_child+":first").remove().hide();
//			_imgFrame.css("marginTop",0);
//			autoPlay(); 
//		});
	};
	
	var autoPlay = function(){
	  _itv = window.setInterval(imgScroller, 3000);
	};
	var autoStop = function(){
		window.clearInterval(_itv);
	};
	if(_imgFrame.find(_child).size()>1){
//	if(_imgFrame.width() < (_width*_imgFrame.find(_child).size())){
		autoPlay();
	}
};
