var empty = /^\s*$/;
var $j = jQuery.noConflict();
//all timeouts should be registered with this array
//so we can clear them with clearAllTimeOuts() function
//if we need to -- this is a work around when a page loaded with timeout
//getting called again via ajax causes the timer to set twice and do the operation
//twice
var g_allTimeOuts = new Object();

$j( document ).ready( function(){
	formEffects();
	tb_register_callback('onload', 'formEffects');
	
	//check if search blank, if so fill with default
	if($j('#searchText').val()==""){
		$j('#searchText').val("search " + $j('#searchType').val());
	}
	
	//bind search focus to function
	$j("#searchText").bind("focus", function(){
    	if($j('#searchText').val().indexOf("search")>-1){
    		$j("#searchText").val("");
    	}
    });
  	//bind search button to check if no search actually entered
  	
  	$j("#searchButton").bind("click", function(){
  		if($j('#searchText').val()=="search " + $j('#searchType').val()){
  			$j("#searchText").val("");
  		}
  		else{
  			$j("#searchText").focus();
  		}
  	});
  	
  	//kill reader links
  	$j("a.reader_link").attr("href", "javascript:void(0)");
});

function revertDisabledSubmit(){
	$j('.disabledButton').remove();
	$j('input[@type=submit]').show();
}

//function gotopage(p){
//	    window.location.href=p;
//}  

function time(){
	return new Date().getTime();
}

//function to apply form affects (in a function so we can call it from thickbox modal as well)
function formEffects(){

	//apply class 'input' to all text, password input fields (ie6 fix)
	$j(':text').addClass("input");
	$j(':password').addClass("input");
	
	//apply focus/blur effects to input fields
	$j('input[@type=text][@readonly=],input[@type=password],select:enabled,textarea[@readonly=]').focus(function(){$j(this).addClass("input_focus");}).blur(function(){$j(this).removeClass("input_focus");});
	
	//disable submit buttons after they're pressed
	//because we may call this function again, first unbind anything attached
	$j(':submit').unbind("click");
/*
	$j(':submit').bind("click", function(e){		
		
		var curClass = $j(this).attr("class");
		$j(this).css("display", "none").after("<input class='disabledButton' type='button' disabled='disabled' value='working..'/>");
		if(curClass!="undefined"){
			$j(".disabledButton").addClass(curClass);
		}
		//$j(this).val("working...").attr("disabled", "disabled");
	});
*/	
}

//function to check if search result is blank
function checkSearch(){
	var s = $j("#searchText").val();
	if(s=="" || s=="search articles" || s=="search publications" || s=="search compilations"){
		flashUnder("#searchBox", "enter a search term above", "error_message", false);
		revertDisabledSubmit();
		$j("#searchText").focus();
		return false;
	}
	else{
		return true;
	}
		
}
function gotopage(p){
	//this is to check if the url already contains the g_webroot portion or not
	var regex_str = "^"+g_webroot.replace(/\//g, "\\\/");
	var regex = new RegExp(regex_str);	
	var http = /^http/;
	
	if( !regex.test(p) && !http.test(p) ){
		p = g_webroot.substr(0,g_webroot.length-1) + p;
	} 
	
	if( window.opener ){
		window.opener.document.location=p;
		
		//close tb if it exists
		if( typeof('tb_remove') != 'undefined' ){
			tb_remove();	
		}
		
		//minimize reader window	
		window.opener.focus();
	} else {
		//check if inside an iframe modal
		if( parent.document.getElementById("TB_iframeContent") ){
			parent.window.location.href=p;	
		}
		else{
			window.location.href=p;
		}
	}
}

function clearAllTimeOuts(){
	for(key in g_allTimeOuts ){
		clearTimeout(g_allTimeOuts[key]);
	}
}

function login_link(just_login){
	
	if( typeof just_login == "undefined"){
		just_login = false;
	}
	
	//title = title || "Login";
	var currUrl = window.location.href;

	var arrQString = new Object();
	arrQString['height'] = 380;
	arrQString['width'] = 400;
	arrQString['next_url'] = encodeURIComponent(currUrl);
	var qString = qs( arrQString );
	
	var link_str = '<a href="javascript:loadTB(\'Login\', \''+g_webroot+'users/login?'+qString+'\');closeFlashMini();">login</a>';
	
	if( !just_login ){
		link_str += ' or <a href="' + g_webroot+'users/signup">signup</a> for free!';
	}
	
	return link_str;
}

var disabledElementColor = null;
var disabledElementFontStyle = null;
function disableElement(element){
	var element = $j( element );
	element.attr("disabled",true);
	disabledElementFontStyle = element.css("font-style");
	element.css("font-style","italic");
	disabledElementColor = element.css("color");
	element.css("color","#ccc");
}
function enableElement(element){
	var element = $j( element );
	element.attr("disabled",false);
	if( disabledElementFontStyle ){
		element.css("font-style", disabledElementFontStyle);
	}
	if( disabledElementColor ){
		element.css("color", disabledElementColor);
	}
}

/**
 *flashes text under an element. e.g. the username availablity check
 *
 * element: DOM element that message should attach to it
 * msg: the message that should appear on it
 * css_class: the css class that defines the style
 * flash: wheter it should flash and disappear once shown
 */
function flashUnder(element, msg, css_class, flash){
	var parent = $j( element ).parent();

	if( typeof(css_class) == "undefined" || !css_class){
		css_class = "under_message_bad";	
	}

	if( typeof(flash) == "undefined" ){
		flash = true;
	}

	$j( parent ).children("#under_message").remove();
	$j( parent ).append( "<div id='under_message' class='"+css_class+"' style='clear:left'>"+msg+"</div>");

	if( flash ){
		$j( "#under_message" ).fadeTo(5000,0, function(){
			$j( "#under_message" ).remove();	
		});
	}
}

/**
 * checks if the global variabl g_is_ajax is defined or not.
 * if this variable is true, the js files know to target certain
 * elements which are ajax specific
 */
function g_is_ajax_defined(){
	return (typeof(g_is_ajax) != "undefined" && g_is_ajax);
}

function loadEditor(id){
	var idUrl = "?";
	if( typeof(id) != "undefined"){
		idUrl += "id="+id;
	} 
	url = g_webroot + "compilations/editor/"+idUrl;
	//loadPage(url, screen.availHeight, screen.availWidth, true);

	//in order to determine if iFrame or new popup (i.e. available window height needs to be at least 675)
	var min_height = 675;
	var avail_height = $j(window).height();
	
	//figure out available height and width of client's screen 
	//if(avail_height>=min_height)
	//	tb_show("Compilations Editor", url + "&TB_iframe=true&height=675&width=980"); //load in iFrame modal
	//else
		loadPage(url,705, 1010, true);
}

function loadFlipBook(id, type, pageNum, userid, extraParams){
	
	//some data checking
	if( typeof(type) == "undefined" ){
		type = "publication";
	}

	if( typeof(extraParams) != "undefined" ){
		//var title = extraParams['title'];
		//var can_tag = extraParams['can_tag'];
		var icon_prefix = extraParams['icon_prefix'];
		var aid = extraParams['aid'];
	}
	
	//in order to determine if iFrame or new popup (i.e. we need at least 675 plus extra space for toolbar etc)
	var min_width  = 1010;
	var min_height = 675;
	var sWidth     = parseInt(screen.availWidth);
	var sHeight    = parseInt(screen.availHeight);
	if(sWidth>1240){min_width = 1250;}
	if(sHeight>800){min_height = 800;}
	
	/*
	var min_width = parseInt(screen.availWidth);
	var min_height = parseInt(screen.availHeight);
	*/
	
	if( type == "publication" ){
		url = g_webroot + "publication/" + id;

	} else if( type == "compilation" ){
		url = g_webroot + "compilation/" + id;

	} else if( type == "article" ){
		url = g_webroot + "publication/" + id + "/"+pageNum;
	}
	
	//load flipbook
	loadPage(url,min_height, min_width, true);
		
}

//close the flipbook modal
function closeFlipBook(){
	//tb_remove();
	fb.close();
}



//close the flipbook modal
function closeFlipBook(){
	//tb_remove();
	fb.close();
}


function g_loadCartContent(){
    if(g_checkEnterprisePermission('allow_ecomm'))
		$j.ajax({
			type: "POST",
			url: g_webroot + "cart/ajax_getCartContents",
			async: true,
			success: function(data){
				$j("#submenu-cart").html(data);
				$j.ajax({
					type: "POST",
					url: g_webroot + "cart/ajax_getCartCount/",
					async: true,
					success: function(data){
						data = JSON.parse(data);
						if(data.count==0) data.count = "0";
						//alert(data.total); //this gives the total amount in the cart
						$j("#cartCount").html( data.count );
						$j("#cart_contents").bind("scroll",function(event){$j('#tool-menu').hide();}); //re-create the bind to hide the menu when scrolling
					}
				});
			}
		});
}

function g_elementExists(id){
	return ( $j(id).get() != "" ); 
}

/**
 * function to preload a set of images using jquery
 */
 
$j.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    $j("<img>").attr("src", arguments[i]);
   
  }
} 
/**
 * a set of images to preload on every page (i.e. logo, tool-menu icons
 */
$j.preloadImages(
 	g_img_url + "img/read.png", 
 	g_img_url + "img/menu_link_bg.gif",
 	g_img_url + "img/menu_link_bg_over.gif",
 	g_img_url + "img/bookmark.png",
 	g_img_url + "img/save.png",
 	g_img_url + "img/email.png",
 	g_img_url + "img/share.png",
 	g_img_url + "img/menu/basket.png",
 	g_img_url + "img/tag.png",
 	g_img_url + "img/edit.png",
 	g_img_url + "img/smiley.png",
 	g_img_url + "img/basket_add.png",
 	g_img_url + "img/basket_delete.png",	
 	g_img_url + "img/delete.png",
 	g_img_url + "img/star-left.png",
 	g_img_url + "img/star-right.png",
 	g_img_url + "img/comment.png",
 	g_img_url + "img/comments.png",
 	g_img_url + "img/flag_red.png",
 	g_img_url + "img/flag_yellow.png"
);


function loadTB(caption, url){
	tb_show(caption,url);
}
function loadTB_WLPC(caption, url,id){
	if( g_isLoggedIn ){
		tb_show(caption,url);
	} else {
		showFlashMini("error","Sorry!","You have to be logged in to do that.<br /><a href='/login'><strong>login now!</strong></a>", "wrapper_"+id);
	}
}

function g_clearBasket(){
	if( g_checkEnterprisePermission('allow_compilations') && confirm("Are you sure you want to remove all articles from your basket?") ){
		$j.ajax({
			type: "POST",
			url: g_webroot + "compilations/ajax_clearCompilationContents/default",
			async: true,
			success: function(data){
				if( data == 1 ){
					//showFlashMessage("success","Success!","Your basket has been emptied.");
					g_loadBasketContent();
				} else if( data == 0 ){
					showFlashMessage("error","Sorry!","Could not empty your basket.");

				} else if( data == "PERMISSION_ERROR" ){
					showFlashMessage("error","Sorry!","You don't have permission to empty the basket");
				}
			},
			error: ajax_communication_error
		});
	}
}

function toggleHideShow(element_id){
	var element = $j("#"+element_id);
	
	if( element.css('display') == 'block' ){
		element.hide();	
	} else  {
		element.show();
	}
}

function ajax_communication_error(){}

function g_checkEnterprisePermission(permission){
    switch(permission){
        case 'allow_compilations':
            return g_allow_compilations;
            break;

        case 'allow_ecomm':
            return g_allow_ecomm;
            break;
    }
    return false;
}

function setValue(selector, value){
	$j( selector ).val( value );
}

function g_clearCart(){
    if(g_checkEnterprisePermission('allow_ecomm') && confirm("Are you sure you want to clear the content of your cart?"))
        $j.ajax({
            type: "POST",
            url: g_webroot + "cart/ajax_clearCart",
            async: true,
            success: function(data){
                if( data == 1 ){
                    g_loadCartContent();
                } else if( data == 0 ){
                    showFlashMessage("error","Sorry!","Could not empty your cart.");

                } else if( data == "PERMISSION_ERROR" ){
                    showFlashMessage("error","Sorry!","You don't have permission to empty the cart");
                }
            },
            error: ajax_communication_error
        });
}

function g_loadBasketContent(){
    if(g_checkEnterprisePermission('allow_compilations'))
        $j.ajax({
            type: "POST",
            url: g_webroot + "compilations/ajax_getCompilationContents/default",
            async: true,
            success: function(data){
                $j("#submenu-basket").html( data );
                $j.ajax({
                    type: "POST",
                    url: g_webroot + "compilations/ajax_getCompilationCount/default",
                    async: true,
                    success: function(data){
                        $j("#basketCount").html( data );
                        $j("#basket_contents").bind("scroll",function(event){$j('#tool-menu').hide();}); //re-create the bind to hide the menu when scrolling
                    }
                });
            }
        });
}

function monitorCountry(select, dataname, stateFieldID, stateField){
	var select = $j(select);
	
	if(typeof dataname == 'undefined')
		dataname = "User";

	if(typeof stateFieldID == 'undefined'){
		stateFieldID = "State";
		stateField   = "state";
	}

	$j("#" + dataname + stateFieldID).removeOption(/./);
	
	if( !empty.test( select.val() ) ){
		var stateSelect = $j("#" + dataname + stateFieldID );
		var parent = stateSelect.parent();
		
		if( typeof g_states[ select.val() ] == "undefined" ){
			//change UserState to a textbox			
			stateSelect.remove();
			parent.append("<input class='input' type='text' name='data[" + dataname + "]["+stateField+"]' id='" + dataname + stateFieldID + "' />");
		} else {
			if( stateSelect.attr("type") == "text" ){
				stateSelect.remove();
				parent.append("<select name='data[" + dataname + "]["+stateField+"]' id='" + dataname + stateFieldID + "' style='width: 247px;'></select>");	
				stateSelect = $j("#" + dataname + stateFieldID);
			}
			stateSelect.addOption( g_states[ select.val() ], false);	
		}
	}
}
