/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

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;
    }
};

var maxChars = 160;
var shown = 0;

$(document).ready(function(){
      $("div.list").hide();
	$("div#locationHolder").hide();
	$("div#previousHolder").hide();
	$("div.transaction").hide();
	
	var rightOptions = {
		titleSelector: 'rel',
		fill: '#F9F3C5',
		cssStyles: {color: 'black', width: 'auto'},
		width: 400,
		padding: 10,
		cornerRadius: 10,
		animate: true,
		spikeLength: 20,
		spikeGirth: 5,
		positions: ['right']
	};
	
	var topOptions = {
		titleSelector: 'title',
		fill: '#F9F3C5',
		cssStyles: {color: 'black', width: 'auto'},
		width: 400,
		padding: 10,
		cornerRadius: 10,
		animate: true,
		spikeLength: 20,
		spikeGirth: 5,
		positions: ['top']
	}
	
	$("a.qualifications").bt(rightOptions)
	$("abbr").bt(rightOptions)
	$("a[title]").bt(topOptions);
	
	if($('a#counter').length)
	{
		msg = $("#message").val();
		len = msg.length;
		$('a#counter').html(maxChars-len+'');
		$('a#counter').css('color', 'green');
	}
	
	$('h3.transactionShow').click(function(event){
		event.preventDefault();
		$(this).next('div.transaction').slideToggle('slow');
	})
	
	$('a[name="selectRecipients"]').toggle(
		function(event){
			event.preventDefault();
			$('input[name="recipient[]"]').attr('checked', 'checked');
		},
		function(event){
			event.preventDefault();
			$('input[name="recipient[]"]').removeAttr('checked');
		}
	)
	
	$('a#viewAllTrans').toggle(
		function(event){
			event.preventDefault();
			$('div.transaction').each(function(){
				$(this).slideDown('slow');
			});
		},
		function(event){
			event.preventDefault();
			$('div.transaction').each(function(){
				$(this).slideUp('slow');
			});
		}
	)
	
	$('a[name="locationLimit"]').click(function(event){
		event.preventDefault();
		$('div#locationHolder').slideToggle('slow');
	})
	
	$('a[name="previousLimit"]').click(function(event){
		event.preventDefault();
		$('div#previousHolder').slideToggle('fast');
	})
	
	$('a[name="groupSelect"]').click(function(){
		$(this).parent().siblings().find('input').each(function(){
                $(this).attr('checked', 'checked');
            });
		return false;
	})
	
	$('a[name="groupUnselect"]').click(function(){
		$(this).parent().siblings().find('input').each(function(){
                $(this).removeAttr('checked');
            });
		return false;
	})
      
      $('h3').click(function(){
            $("div#list"+this.id).slideToggle();
            return false;
      })
	
	$('a#expandAll').click(function(){
		$('div#lists > div').show('slow');
		return false;
	})
	
      $('a#contractAll').click(function(){
		$('div#lists > div').hide('slow');
		return false;
	})
      
      $('a#selectAll').click(function(){
            $("input[type='checkbox']").attr('checked', 'checked');
		return false;
      })
      
      $('a#unselectAll').click(function(){
            $("input[type='checkbox']").attr('checked', '');
		return false;
      })
      
	function adjustCounter()
	{
		msg = $('textarea#message').val();
            len = msg.length;
            if(len<maxChars)
            {
                  $('a#counter').html(maxChars-len+'');
                  $('a#counter').css('color', 'green');

            }else{
                  $('a#counter').html('0');
                  $('a#counter').css('color', 'red');
                  if(len>maxChars)
                  {
                        msg = msg.substring(0, maxChars);
                        $('textarea#message').val(msg);
                  }
            }
	}
	
	$('textarea#message').focus(function(){
		if(shown==0){
			$('a.thickbox').click();
			shown=1;
		}
      })
	
	$('input#tb_rem').click(function(){
		tb_remove();
		$('textarea#message').focus();
	})
		
	$('textarea#message').keyup(function(){
            adjustCounter();
      })
	
	$('input[value="basic"]').click(function(){
		$('#message').val($('input[name="basicText"]').val());
		$('#message').val($('#message').val()+"\n\n");
		adjustCounter();
	})
	
	$('input[value="enhanced"]').click(function(){
		$('#message').val($('input[name="enhancedText"]').val());
		$('#message').val($('#message').val()+"\n\n");
		adjustCounter();
	})
	
	$('a[name="resetMessage"]').click(function(event){
		event.preventDefault();
		newval = $('input[name="default"]').val();
		$('textarea#message').val(newval);
		
		msg = '<span style="display:inline; margin-left:30px;" id="resetMsg">Your message has been reset!</span>';
		$(this).after(msg);
		$('span#resetMsg').css({color: 'red'}).fadeOut(1500);
		
		$('input[value="basic"]').attr('checked', 'checked');
		lastChecked = 'standard';
		
		if($('span#alert').html()!='')
		{
			$('span#alert').html('');
		}
		adjustCounter();
	})
	

	$('#hidden').hide();
	$('label#showList').click(function(){
		$('#hidden').show('slow');	
	});
	
	$('select#health_boards').change(function(){
		$('input#board').val("").attr('disabled', true);
	})
	
	$('select[name="country"]').change(function(){
		country = $(this).val();
		if(country == "")
		{
			text = '<option value="">Choose country first</option>';
			$('select[name="location"]').html(text).attr('disabled', true);
			$('select[name="health_board"]').html(text).attr('disabled', true);
			return false;
		}else{
			$('img#loader').css('display', 'inline');
			
			$.post("http://www.locummonkey.co.uk/arealist/index", {c: country},
			function(data){
				$('select[name="location"]').html(data).attr('disabled', false);
				$('img#loader').css('display', 'none');
			});
			
			if($('select[name="health_board"]').length)
			{
				$.post("http://www.locummonkey.co.uk/arealist/healthboards", {c: country},
				function(data){
					$('select[name="health_board"]').html(data).attr('disabled', false);
					$('img#loader').css('display', 'none');
				});
			}			
			return false;
		}
	})
	
	$('a[name="selectEnglish"]').toggle(
		function(){
			$('input.english').attr('checked', true);
			return false;
		},
		function(){
			$('input.english').attr('checked', false);
			return false;			
		}
	)
	
	$('a[name="selectScottish"]').toggle(
		function(){
			$('input.scottish').attr('checked', true);
			return false;
		},
		function(){
			$('input.scottish').attr('checked', false);
			return false;			
		}
	)
	
	$('a[name="selectWelsh"]').toggle(
		function(){
			$('input.welsh').attr('checked', true);
			return false;
		},
		function(){
			$('input.welsh').attr('checked', false);
			return false;			
		}
	)
	
	$('a[name="selectIrish"]').toggle(
		function(){
			$('input.irish').attr('checked', true);
			return false;
		},
		function(){
			$('input.irish').attr('checked', false);
			return false;			
		}
	)
        
	$('input[name="delaccount"]').click(function(e){
	    var val = $('textarea[name="reason"]').val();
	    if(val.length > 0)
	    {
		    if(confirm('Are you sure you want to permanently delete your account? This cannot be undone!'))
		    {
			    return true;
		    }else{
			    e.preventDefault();
			    return false;
		    }
	    }else{
		    return true;
	    } 
	})
	  
	$('a[name="togglePrevious"]').toggle(
		function(){
			$('select[name="excludeTrans[]"] > option').attr('selected', 'selected');
		},
		function(){
			$('select[name="excludeTrans[]"] > option').removeAttr('selected');
		}
	)
	
	$('a#counter').click(function(e){
		e.preventDefault();
	})
        
      $('#email').focus(function(){
            if($(this).val()=='email'){
                  $(this).val('');
            }
      });
      
      $('#email').blur(function(){
            if($(this).val()==''){
                  $(this).val('email');
            }
      });
      
      $('#password').focus(function(){
            if($(this).val()=='password'){
                  $(this).val('');
            }
      });
      
      $('#password').blur(function(){
            if($(this).val()==''){
                  $(this).val('password');
            }
      });
      
      if($('body.loggedin').length){
        if(!$.cookie("pop_url")){
            
            var links = $('#left-lower').find('a');
            var locs = [];
            
            links.each(function(){
                locs.push($(this).attr('href'))
            });
            
            var linknum = Math.floor(Math.random()*locs.length);
            $.cookie("pop_url", links[linknum]);
            
            var newwin = window.open(links[linknum], "", "height=800,width=1000");
            newwin.blur();
            window.setTimeout(function(){
               window.focus();
            }, 2000);
        }
      };
      
      $('.logout_pop').bind("click", function(){
        var links = $('#left-lower').find('a');
        var locs = [];
        
        links.each(function(){
            var href = $(this).attr('href');
            if(href != $.cookie("pop_url")){
                locs.push(href);                
            }
        });
        
        var linknum = Math.floor(Math.random()*locs.length);
        
        var newwin = window.open(links[linknum], "", "height=800,width=1000");
        newwin.blur();
        window.setTimeout(function(){
           window.focus();
        }, 2000);
        
        $.cookie("pop_url", null);
      });
})

function conf_go(msg, url)
{
	if(confirm(msg))
	{
		window.location.href=url;
	}
}
