jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

// browser warn
$(window).load(function(){
    if(($.browser.msie && $.browser.version>="7") || ($.browser.mozilla && $.browser.version.substr(0,3)>="1.9") || ($.browser.safari && $.browser.version.substr(0,3)>="522")){
    // browser pass
    }
    else {
        if ($.cookie('browser_warn')==null) {
            tb_show('','/browser_warn?height=300&width=680&modal=true&keepThis=true','');
            // set cookie
            $.cookie('browser_warn', 'browser_warn', {
                path: '/'
            });
        }
    
    }
});

// flash warn
// $(window).load(function(){
//   if(FlashDetect.major > 9){
//     // flash pass  
//     //alert("Flash major: "+ FlashDetect.major);       
//   }
//   else {
//     if ($.cookie('flash_warn')==null) {
//       tb_show('','/flash_warn?height=300&width=680&modal=true&keepThis=true','');
//       // set cookie
//       $.cookie('flash_warn', 'flash_warn', {
//       path: '/'
//       });
//     }
//   }
// });

// make logo clickable to home

$(document).ready(function(){
    $('#header #logo').click(function(){
        window.location.href = '/';
    })
});

// left nav filter
$(document).ready(function(){
    // if ($('#categories .all').attr('checked')) {
    //         $('#categories #all_c').attr('checked', true);
    //     }
    if ($('#categories #all_c').attr('checked')) {
        $('#categories input:checkbox').attr('checked', true);
        $('#categories .all').parent().hide();
    }
    $('#categories #all_c').click(function(){
        if ($('#categories #all_c').attr('checked')) {
            $('#categories input:checkbox').attr('checked', true);
            $('#categories .all').parent().hide();
        }
        else {
            $('#categories #all_c').attr('checked', false)
            $('#categories input:checkbox').attr('checked', false);
            $('#categories .all').parent().show();
        }
    });
    $('#categories .all').click(function(){
        $('#categories #all_c').attr('checked', false);
    });
});

$(document).ready(function(){ 
    // if ($('#frequency .all').attr('checked')) {
    //         $('#frequency #all_f').attr('checked', true);
    //     }
    if ($('#frequency #all_f').attr('checked')) {
                $('#frequency input:checkbox').attr('checked', true);
                $('#frequency .all').parent().hide();
            }
    $('#frequency #all_f').click(function(){
        if ($('#frequency #all_f').attr('checked')) {
            $('#frequency input:checkbox').attr('checked', true);
            $('#frequency .all').parent().hide();
        }
        else {
            $('#frequency #all_f').attr('checked', false)
            $('#frequency input:checkbox').attr('checked', false);
            $('#frequency .all').parent().show();
        }
    });
    $('#frequency .all').click(function(){
        $('#frequency #all_f').attr('checked', false);
    });
});

$(document).ready(function(){ 
    // if ($('#range .all').attr('checked')) {
    //         $('#range #all_r').attr('checked', true);
    //     }
    // if ($('#range #all_r').attr('checked')) {
    //                 $('#range .all').parent().hide();
    //             }
    $('#range #all_r').click(function(){
        if ($('#range #all_r').attr('checked')) {
            $('#range input:radio').attr('checked', false);
            $('#range .all').parent().hide();
        }
        else {
            $('#range #all_r').attr('checked', false)
            $('#range input:radio').attr('checked', false);
            $('#range .all').parent().show();
        }
    });
    $('#range .all').click(function(){
        $('#range #all_r').attr('checked', false);
    });
});

$(document).ready(function(){
  $('#savesearch').hide();
    $('#left_nav #filter').click(function(){
        var cats = [];
        $("#categories input:checkbox:checked").each(function(){
            cats.push($(this).val());
        });
        if (isNaN(cats[0])==true) cats.shift();
    
        var freqs = [];
        $("#frequency input:checkbox:checked").each(function(){
            freqs.push($(this).val());
        });
    

        var range = '-1';
        if ($('#range #all_r').attr('checked')) {
            range = '0';
        }
        else {
            $("#range input:radio:checked").each(function(){
                range = ($(this).val());
            });
        }

    
        if (cats.length<1) {
            alert("Please select at least one Category filter.")
        }
        else if (range == '-1' && window.location.href.indexOf('publications') < 1) {
            alert("Please select a valid date range.")
        }
    
        else {
            //var data = "category_ids="+cats.toString();
            var data = "category_ids="+cats.toString()+"&frequency="+freqs.toString()+"&range="+range.toString();  
            //alert(data)
            get_data(String(location), 'GET', data, display_ordering_callback);
            $.blockUI({
                message: '<img src="/images/timer.gif" />'
            });
          
          $('#saved_search select').val("")  
          $('#savesearch').show();
        }
    });
});

$(document).ready(function(){
    $('#left_nav #save').click(function(){
        $('#left_nav #name').show();
        $('#left_nav #ok').show();
    });
});

$(document).ready(function(){
    $('#name').focus(function(){
        $('#left_nav #name').val('');
    });
});

$(document).ready(function(){
  $('#left_nav #savesearch #ok').click(function(){
    if ($('#left_nav #savesearch #name').val()=='' || $('#left_nav #savesearch #name').val()=='Name this filter') alert('Please type a name for this filter')
    else { 
      document.location.href = "/users/save_filter?name="+$('#left_nav #savesearch #name').val();  
    }
  });
});

$(document).ready(function(){
    $('#saved_search select').change(function(){
        if ($('#saved_search select').val()>0) document.location.href = "/apply_filter/"+($('#saved_search select').val());
    });
});

///////////////////////////////////////////////////////
// clear Search text onfocus

$(document).ready(function(){
    $('#searchbox #q').focus(function(){
      $('#searchbox #q').select();
    })
    $('#searchbox #q2').focus(function(){
      $('#searchbox #q2').select();
    })
    $('#searchbox #qsearch').focus(function(){
      $('#searchbox #qsearch').select();
    })
    $('#searchbox #q404').focus(function(){
      $('#searchbox #q404').select();
    })
});
///////////////////////////////////////////////////////
// Clear form values (universal)

jQuery(document).ready(function(){
    jQuery(".search_form_clear").click(function(){
        var elems = document.forms[1].elements;
        for (i=0;i<elems.length;i++){
            var type = elems[i].type, tag = elems[i].tagName.toLowerCase();
            if (type == 'text' || type == 'password' || tag == 'textarea')
                elems[i].value = '';
            else if (type == 'checkbox' || type == 'radio')
                elems[i].checked = false;
            else if (tag == 'select')
                elems[i].selectedIndex = -1;
        }
        jQuery("#left_nav .all").parent().show();
    });
})
///////////////////////////////////////////////////////
$(document).ready(function(){ 
    $("#favorites #bookmarked a").click(function(){
		$("#favorites #recent").html($("#favorites #bookmarks").html());	
    });
	$("#favorites #fav_pubs #menu a").click(function(){
		$("#favorites #recent").html($("#favorites #general #edit").html());	
    });
	$("#favpubs div div:first-child a:last-child").click();
	//$("#favpubs div div:first-child a:last-child").css('font-weight','bold');
});

$(function(){
    $("#favorites #bookmarked a").click(function(){
        var data = "";
        get_data(String(location), 'GET', data, display_ordering_callback );
        $.blockUI({
            message: '<img src="/images/timer.gif" />'
        });
        //test();
      });
});
///////////////////////////////////////////////////////
// style info tables (latest news etc)

function stylerows() {													 
	for (i=1;i<$(".table_style li").length;i++) {
		if (i/2 != parseInt(i/2)) {
			$(".table_style li:eq("+i+")").css("background-color", "#F9F9F9");
			$(".table_style li:eq("+i+")").css("border-bottom", "1px solid #F0F0F0");
		}
		else {	
			$(".table_style li:eq("+i+")").css("border-bottom", "1px solid #EEE");
		}	
		 					
	}
	$(".table_style li.row").click(function(){ 
		for (i=1;i<$(".table_style li").length;i++) {
			if (i/2 != parseInt(i/2)) {
				$(".table_style li:eq("+i+")").css("background-color", "#F9F9F9");
				$(".table_style li:eq("+i+")").css("border-bottom", "1px solid #F0F0F0");
			}
			else {	
				$(".table_style li:eq("+i+")").css("background-color", "#FFF");
				$(".table_style li:eq("+i+")").css("border-bottom", "1px solid #EEE");
			}	
		 					
		}
		$(this).css("background-color", "#b7fb5a");
	});
}

$(document).ready(function(){	
  if ($(".row").length > 0) {
    stylerows();
  }
});

///////////////////////////////////////////////////////
// preview issue (latest news etc)
/*
$(document).ready(function(){
	$('.blockslist .row').click(function(){	 
		alert('click') 
		preview($(this));
	});
});	
*/
	function preview(which) {
	//	alert(which.html())
	//remove delete icon and checkbox from "which" html
		$('#preview li').html(which.html());
		$('#preview p').html('<img src="'+$('img',which).attr('src')+'"/>'+$('input[type=hidden]',which).val()+' <a href="'+$('a',which).attr('href')+'">more&nbsp;&#8658;</a>');
    }

// preview issue in modal
function preview_modal() {
  $("div a").click( function(event)
  {
     var clicked = $(this); // jQuery wrapper for clicked element
     // ... click-specific code goes here ...
  });
}



// disable submit on form submit
jQuery(document).ready(function(){
  var timer = new Image();
  timer.src = '/images/timer.gif';
  jQuery('form').submit(function() {
      jQuery.blockUI({
          message: '<img src="/images/timer.gif" />'
      });
  });
    // var timer = new Image();
    // timer.src = '/images/timer.gif';
    // jQuery('form').submit(function() {
    //     jQuery.blockUI({
    //         message: '<img src="/images/timer.gif" />'
    //     });
    // });

    // $(document).ajaxComplete(function() {
    //    jQuery.unblockUI();
    // });
});
///////////////////////////////////////////////////////
// Remove non integers
function validated(string) {
for (var i=0, output='', valid="0123456789"; i<string.length; i++)  
  if (valid.indexOf(string.charAt(i)) != -1)
    output += string.charAt(i)
return output;
}

$(document).ready(function(){
  $('#billing_account_billing_address_attributes_phone').blur(function(){
    document.getElementById('billing_account_billing_address_attributes_phone').value = validated($('#billing_account_billing_address_attributes_phone').val())
  })
});
///////////////////////////////////////////////////////
// format state select for billing page
$(document).ready(function(){
  //$('#billing_account_billing_address_attributes_state option:eq(1)').before("<option value='0' style=\"font-size:13px;font-weight:bold;margin-left:0px;background:#FFFFCC;border-bottom:1px solid #333;\">USA</option>");
  //$('#billing_account_billing_address_attributes_state option:eq(53)').before("<option value='0' style=\"font-size:13px;font-weight:bold;margin-left:0px;background:#FFFFCC;border-bottom:1px solid #333;\">CANADA</option>");
});

///////////////////////////////////////////////////////
// alerts mouseover
$(function(){
    $(".form_alerts tr").hover(function()
    {
        $(this).addClass("highlight");
    },
    function(){
        $(this).removeClass("highlight");
    }
    )
})



///////////////////////////////////////////////////////
// hide alert box

$(document).ready(function(){
    setTimeout(function() {
        $('#alert_box').fadeOut('slow');$('#alert').slideUp('slow')
    },5000);
});



///////////////////////////////////////////////////////
// help page FAQ

$(document).ready(function(){
    $('#accordion h4').click(function() {
        $.browser.msie?$(this).next().toggle():$(this).next().toggle('slow');
        return false;
    }).next().hide();
	
    $('#accordion #expand').click(function() {
        $.browser.msie?$('#accordion div').show():$('#accordion div').show('slow');
    });
	
    $('#accordion #close').click(function() {
        $.browser.msie?$('#accordion div').hide():$('#accordion div').hide('slow');
    });
});

///////////////////////////////////////////////////////
// highlight bundle in bundle options
$(document).ready(function(){
  $("#select_bundle .form_box input").click(function(){
	$("#select_bundle .form_box").css("background-color","#FFCC55")
    $(this).parent().parent().css("background-color","#81DB05")
  })  
});


///////////////////////////////////////////////////////
// Tooltip

/*
 * Tooltip script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */

this.tooltip = function(){	
    /* CONFIG */
    xOffset = 10;
    yOffset = 20;
    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result
    /* END CONFIG */
    $(".tooltip").hover(function(e){
        this.t = this.title;
        this.title = "";
        $("body").append("<p id='tooltip'>"+ this.t +"</p>");
        $("#tooltip")
        .css("top",(e.pageY - xOffset) + "px")
        .css("left",(e.pageX + yOffset) + "px")
        .fadeIn("fast");
    },
    function(){
        this.title = this.t;
        $("#tooltip").remove();
    });	
    $("a.tooltip").mousemove(function(e){
        $("#tooltip")
        .css("top",(e.pageY - xOffset) + "px")
        .css("left",(e.pageX + yOffset) + "px");
    });
};


// starting the script on page load
$(document).ready(function(){
    tooltip();
});
///////////////////////////////////////////////////////
// Sort & Views

$(function(){
    $('.view').change(function(){
        elem = $('input#view');
        if(elem.length > 0){
            elem.remove();
        }
        var data = "view="+$(this).val().toLowerCase();
        get_data(String(location), 'GET', data, display_ordering_callback );
        $.blockUI({
            message: '<img src="/images/timer.gif" />'
        });
        //test();
      });
  
    // Sorting
    $('.sort').change(function(){
        elem = $('input#order');
        if(elem.length > 0){
            elem.remove();
        }
        var data = "order="+$(this).val().toLowerCase();
        get_data(String(location), 'GET', data, display_ordering_callback);
        $.blockUI({
            message: '<img src="/images/timer.gif" />'
        });
    	//test();
    });
  
});
///////////////////////////////////////////////////////
//
var get_data = function(url, type, data, callback, data_type){
    $.ajax({
        url: url.replace('#',''),
        cache: false,
        type: type,
        data: data,
        dataType: data_type || 'html',
        success: function(data){
            callback(data);
        }
    });
    return(false);
};

var display_ordering_callback =  function(data){
    // replace data with new view
    $("#hidden_params").remove();
    $(".pagination").remove();
    $(".textblocks").replaceWith(data);	

    $.unblockUI();
    $(document).ready(function(){
        if ($(".row").length > 0) {
            stylerows();
        }
		if ($(".fav_icon").length > 0) {
			chk_favs();
		}
    });
  
}; //end function

///////////////////////////////////////////////////////
// Signin control

var form_url = function(elem){
    url = elem.attr('action');
    if(url == 'javascript:void(0)'){
        url = elem.attr('action_url');
    }
    else{
        elem.attr('action', 'javascript:void(0)');
        elem.attr('action_url', url);
    }
    return url;
}


///////////////////////////////////////////////////////
// open thickbox from within a thickbox

var jThickboxNewLink;
function tb_remove_open(reloadLink){
    jThickboxReloadLink	=	reloadLink;
    tb_remove();
    setTimeout("jThickboxNewLink();",500);
    return false;
}

function tb_open_new(jThickboxNewLink){
    tb_show(null,jThickboxNewLink,null);
}

///////////////////////////////////////////////////////
// modals

var submit_signin_modal = function(){
    error = $('#signin_form p.red');
    error.empty();
 
    var data = "user_session[email]="+$("input[name='user_session[email]']").val() +"&"
    data = data + "user_session[password]="+$("input[name='user_session[password]']").val();
    if($("input[name='remember_me']").attr('checked')){
        data = data + "&remember_me=true";
    }
  
  
    get_data(form_url($('form#signin_form')), 'POST', data, function(data){
        if(data["redirect_url"]){
            //tb_remove();
            $(".modalpage h3").html('<strong>Thanks for signing in!</strong>');
            $(".modalpage .form").html('<br /><br /><br />Please be patient while the application loads.</p>');
            location = data["redirect_url"];
        }
        else if(data["error"]){
            error.html(data["error"]);
        }
    },"json");
  
};

var submit_register_modal = function(){

    error = $('form#registration_form p.red');
    error.empty();
  
    var data = "user[email]=" + $("input[name='user[email]']").val() +"&";
    data = data + "user[password]=" + $("input[name='user[password]']").val() +"&";
    data = data + "user[first_name]=" + $("input[name='user[first_name]']").val() + "&";
    data = data + "user[last_name]=" + $("input[name='user[last_name]']").val();
    /*  if($("input[name='agreed_terms_and_conditions']").attr('checked')){
    
  }
*/  
    var url = form_url($('form#registration_form'));

    if (document.registration_form.elements[4].checked == true) {
        data = data + "&user[agreed_to_terms_and_conditions]=true";
        get_data(url, 'POST', data, function(data){
    
            if(data['redirect_url']){
                //tb_remove();
                $(".modalpage .regform").html('<br /><br /><br /><strong>Thanks for registering!</strong><p>Please be patient while the application loads.</p>');
                location = data['redirect_url'];
            }
            else if(data['error']){
                error.html(data['error'].join('<br />'));
            }
        },"json");
    }
    else {
        alert('Please read and agree to the Terms & Conditions')
    }
};

var submit_forgot_password_form = function(){
    error = $('form#forgot_password_form p.red');
    error.empty();
    var data = "email=" + $("input[name='email']").val();
    get_data(form_url($('form#forgot_password_form')), 'POST', data, function(data){
        if(data["success"]){
            tb_remove();
            location.reload();
        }
        else if(data["error"]){
            error.html(data["error"]);
        }
    },'json');
};

// // Helper function for Javascript object inspection
// var MAX_DUMP_DEPTH = 10;      
// function dumpObj(obj, name, indent, depth) {
//        if (depth > MAX_DUMP_DEPTH) {
//               return indent + name + ": <Maximum Depth Reached>\n";
//        }
//        if (typeof obj == "object") {
//               var child = null;
//               var output = indent + name + "\n";
//               indent += "\t";
//               for (var item in obj)
//               {
//                     try {
//                            child = obj[item];
//                     } catch (e) {
//                            child = "<Unable to Evaluate>";
//                     }
//                     if (typeof child == "object") {
//                            output += dumpObj(child, item, indent, depth + 1);
//                     } else {
//                            output += indent + item + ": " + child + "\n";
//                     }
//               }
//               return output;
//        } else {
//               return obj;
//        }
// }

///////////////////////////////////////////////////////
// favorites tabs
$(document).ready(function(){
	$('#favorites ul#menu li a').click(function(){
		$('#favorites ul#menu li a').removeClass('active');
		$(this).addClass('active');
	});
	$('#favorites ul#menu li a#fav-pubs').click(function(){
		//$('#stage').load('/favorite_pubs');
	});
});

function lightStar(pubId){
	var c;
	if (favs.indexOf(pubId) > -1){
		c = 'fav_icon';
	}
	else{
		c = 'fav_icon_on';
	}
	var o = $('#' + pubId);
	o.removeClass();
	o.addClass(c);
	//alert("Successfully updated Favorites");
}

// Add pub to favorites
function create_favorite(pubID,which) {
	$.ajax({
	        data:'fav_ids='+ pubID + '&which=' + which,
	        dataType:'script',
	        type:'post',
	        url:'/users/create_favorite_publications',
			success: lightStar(pubID)
	    });
	//chk_favs();
}

// Check favs in publications
$('#publications').ready(function(){
	chk_favs();
});

function chk_favs() {
	var icons = $('#publications .fav_icon')
	for(i=0;i<icons.length;i++) {
		for(j=0;j<favs.length;j++) {
			if (icons[i].id == favs[j]) {
				//alert(icons[i].id)
				icons[i].style.backgroundImage = 'url(/images/icon_star_on.gif)';
				icons[i].title = "Favorite Publication"
			}
		}
	}
	//window.location = window.location.href;
}

///////////////////////////////////////////////////////
function create_bookmark(param1,param2) {
    $.ajax({
        data:'content_id='+ param1 + '&type=' + param2.innerHTML + '&authenticity_token=' + window._token,
        dataType:'script',
        type:'post',
        url:'/users/create_favorite_issue'
    });
}

//This method is called on ajax callback
function toggle_bookmark(param){
    status = jQuery.trim($("#bookmark_toggle").html());
    status == "Bookmark" ? $('#bookmark_toggle').html('Remove Bookmark') : $('#bookmark_toggle').html('Bookmark');
    if(param)
        alert ("Error while bookmarking the publication.");
    else
        alert(status + " Successful.");
		
}
///////////////////////////////////////////////////////
//
function removeSearchItem(item_id){
  if (confirm('Delete this search term?')) { 
    $.ajax({
        data:'item_id='+ item_id + '&authenticity_token=' + window._token,
        dataType:'script',
        type:'get',
        url:'/users/remove_search_item'
    });
  }
}

function add_search_item(){
    var item_name = $("#new_top_search").val();
    if(item_name.length > 0) {
        $.ajax({
            data:'item_name='+ item_name + '&authenticity_token=' + window._token,
            dataType:'script',
            type:'get',
            url:'/users/add_search_item'
        });
    }
    return false;
}

function add_search_result(item_name, item_id){
    if(item_id != "0"){
         var drag_img = "<img src='/images/arrow.png' alt='move' width='16' height='16' class='handle' />";
         var text = "<a href='/search?q="+item_name+"'><strong>" + item_name + "</strong></a>&nbsp;&nbsp;"
         var del_img = "<img src='/images/icon_del.gif' alt='Delete this item' style='cursor:pointer; position:relative; top:2px; left:2px;' onclick=\"return removeSearchItem('" + item_id +"');\" />";

        alert("Search Item added to the list at the bottom.");
        $("#search_list").append("<li id='listItem_" + item_id + "' style='margin-left:0;'>" + drag_img + text + del_img + "</li>");
    }
    else{
        alert("Error. Search item not added.");
    }
}

///////////////////////////////////////////////////////
// Remove filter item

function removeFilterItem(id){
  if (confirm('Delete this filter?')) { 
    $.ajax({
      data:'item_id='+ id + '&authenticity_token=' + window._token,
      dataType:'script',
      type:'get',
      url:'/users/remove_filter'
    });
  }
}

function updatePageWithFilter(id){
	if (id == 'undefined' || id == null)
	{
		if ($("#saved_filters_list").val() == 'choose'){
			return;
		}
		if ($("#saved_filters_list").val() == 'edit'){
			window.location = '/users/filters';
			return;
		}else{
			$.blockUI({
		        message: '<img src="/images/timer.gif" />'
		    });
			id = $("#saved_filters_list").val();
		}
	}
	window.location = '/apply_filter/' + id;
}