/* prevent execution of jQuery if included more than once */

/*
 * Interface javascript, extending jQuery
 *---------------------TOC:---------------------
 * 1. drag n drop
 * 2. addLoadevent -> Loads the functions as browser loads the page
 * 3.
 * $Date: 20June2007
 */
$(document).ready(function(){

})
var dragger = function () {
			$("a.drag-me").css("cursor", "move");
			var dragItem = $('.mod');
				$('#sn_userinfo, #sn_whatsnew').addClass('no-move');
			$('div.mod-col').Sortable(
				{
					accept: 'mod:not(.no-move)',
					helperclass: 'sort-helper',
					activeclass : 'sortableactive',
					hoverclass : 'sortablehover',
					handle: 'h3.handle',
					handle: 'a.drag-me',
					tolerance: 'pointer',
					revert: true,
					floats: true,
					opacity: 		0.8,

					onChange : function(ser)
					{
						
					},
					onStart : function()
					{	
						 // $.iAutoscroller.start(this, document.getElementsByTagName('body'));
						//$.autoscroll.init({mod_key: '', trigger:'50'});
						
					},
					onStop : function()
					{
						$.iAutoscroller.stop();
						var modPosition = $.SortSerialize(['sn_col1', 'sn_col2', 'sn_col3']).hash;
						//alert(modPosition);
						//:: accounts/modulesort
						$.ajaxSetup({
							url: '/accounts/modulesort/',
							global: false,
							type: 'POST'
						});
						$.ajax({data: modPosition});
					}
				}				
			);
			
		}
var showConfirm = function(message){
	$("body","html").css({height: "100%", width: "100%"});
	$("html").css("overflow","hidden");
	if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
		$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
		$('#TB_window').css({display:'block', margin:'-66px 0 0 -150px', padding: '10px'});
		$('#TB_window').width('300px');
		$('#TB_window').height('100px');
		$("#TB_window").append(message);
		$(this, '#TB_window').click(function(){tb_remove()});
		$(this, '#TB_close').click(function(){tb_remove()});
	}
}
var confirmPopup = function(mess,callback){
		
		if (typeof callback != 'function') {
			var follow=callback;
			callback = function() { window.location.href = follow; }
		}
		
		$('#sn_wrap').before('<div class="sn_alert_pop"  style="display:none" id="sn_alert_popID">'+mess+'<span id="close-style-box">X</span><p><form><input type="button" id="sn_alert_button_yes" value="Yes" />&nbsp;<input type="button" id="sn_alert_button_no" value="No" /></form></p></div>')
		$('.sn_alert_pop').fadeIn('fast');
		$('#close-style-box').click(function(){$('.sn_alert_pop').remove();});
		$('#sn_alert_button_yes').click(function(){$('.sn_alert_pop').remove();callback();return true;});
		$('#sn_alert_button_no').click(function(){$('.sn_alert_pop').remove();});

}
var toggleContent = function(e)
	{
		var targetContent = $('div.mod-body', this.parentNode.parentNode);
		if (targetContent.css('display') == 'none') {
			targetContent.slideDown(300);
			$(this).html('[-]');
		} else {
			targetContent.slideUp(300);
			$(this).html('[+]');
		}
		return false;
	};
	function serialize(type, s)
	{
		if (type == 'sort') {serial = $.SortSerialize(s)} else{return false};
		if (type == 'select') {serial = $.SelectSerialize(s)} else{return false};
		return serial;
		//alert(serial.hash);
	};
	
//alerts
var sendAlert = function(mess, typeOf, timing){
		$(".sn_alert_pop").remove();
		$(".sn_alert_pop2").remove();
		if (typeOf == 'good') {
			$('#sn_wrap').before('<div class="sn_alert_pop" style="display:none"  id="sn_alert_popID"><div id="sn_alert_messages">'+mess+'</div><span id="close-style-box">X</span></div>')
			$('.sn_alert_pop').fadeIn('slow').animate({opacity: 1.0}, timing).fadeOut('slow', function(){if(this.parentNode){$(this).remove();}});
		}
		else if (typeOf == 'bad') {
			$('#sn_wrap').before('<div class="sn_alert_pop2"  style="display:none"  id="sn_alert_popID"><div id="sn_alert_messages">'+mess+'</div><span id="close-style-box">X</span></div>')
			$('.sn_alert_pop2').fadeIn('slow').animate({opacity: 1.0}, timing).fadeOut('slow', function(){if(this.parentNode){$(this).remove();}});
		}
		$('#close-style-box').click(function(){$('#sn_alert_popID').remove()})
}	
var xPos=0;
var yPos=0;
jQuery(document).ready(function(){
	$().click(function(e){
		xPos=e.pageX;
		yPos=e.pageY;
	}); 
})
var sendAlertAtCursor = function(mess){
	$(".sn_alert_pop").remove();
	$(".sn_alert_pop2").remove();
	//alert(xPos+" "+yPos);
	$('#sn_wrap').before('<div class="sn_alert_pop" style="display:none" id="sn_alert_popID">'+mess+'<span id="close-style-box">X</span></div>');

	$('#sn_alert_popID').css("position","absolute");
	$('#sn_alert_popID').css("left",(xPos+($('#sn_alert_popID').width()/2)));
	$('#sn_alert_popID').css("top",(yPos));


	$('#sn_alert_popID').fadeIn('slow');
	$('#close-style-box').click(function(){$('#sn_alert_popID').remove();});

}
var sendAlertAtCursorDeleteConfirm = function(mess){
	$(".sn_alert_pop").remove();
	$(".sn_alert_pop2").remove();
	$('#sn_wrap').before('<div class="sn_alert_pop3" style="display:none" id="sn_alert_popID">'+mess+'<span id="close-style-box">X</span></div>');

      if (navigator.userAgent.indexOf('MSIE 6.0')!= -1){
        $('#sn_alert_popID').css("position","absolute");
      	$('#sn_alert_popID').css("left",'1000px');
      	$('#sn_alert_popID').css("top",'1100px');
      }else{
      $('#sn_alert_popID').css("position","fixed");
      	$('#sn_alert_popID').css("left",'100%');
      	$('#sn_alert_popID').css("top",'100%');
      }  


	$('#sn_alert_popID').fadeIn('slow');
	$('#close-style-box').click(function(){$('#sn_alert_popID').remove();});

}
var sendAlertAtCursorComments = function(mess){
	$(".sn_alert_pop").remove();
	$(".sn_alert_pop2").remove();
	//alert(xPos+" "+yPos);
	$('#sn_wrap').before('<div class="sn_alert_pop" style="display:none" id="sn_alert_popID">'+mess+'<span id="close-style-box">X</span></div>');

	$('#sn_alert_popID').css("position","absolute");
	$('#sn_alert_popID').css("min-width",(450));
	$('#sn_alert_popID').css("top",(451));


	$('#sn_alert_popID').fadeIn('slow');
	$('#close-style-box').click(function(){$('#sn_alert_popID').remove();});

}
var sendAlertAtCursorOwner= function(mess){
	$(".sn_alert_pop").remove();
	$(".sn_alert_pop3").remove();
	$('#sn_wrap').before('<div class="sn_alert_pop3" style="display:none" id="sn_alert_popIDTest">'+mess+'<span id="close-style-box">X</span></div>');

      if (navigator.userAgent.indexOf('MSIE 6.0')!= -1){
       // $('#sn_alert_popIDTest').css("margin-left",'-300px');
        $('#sn_alert_popIDTest').css("position","absolute");
      	$('#sn_alert_popIDTest').css("left",'107%');
      	$('#sn_alert_popIDTest').css("top",'170%');
      }else{
       	$('#sn_alert_popIDTest').css("position","fixed");
        //$('#sn_alert_popIDTest').css("left",'100%');
        //$('#sn_alert_popIDTest').css("top",('90%'));
        $('#sn_alert_popIDTest').css("left",'400px');
        $('#sn_alert_popIDTest').css("top",('100px'));
     }  


	$('#sn_alert_popIDTest').fadeIn('slow');
	$('#close-style-box').click(function(){$('#sn_alert_popIDTest').remove();});

}
var sendAlertAtCursorDemote= function(mess){
	$(".sn_alert_pop").remove();
	$(".sn_alert_pop4").remove();

	//alert(xPos+" "+yPos);
	$('#sn_wrap').before('<div class="sn_alert_pop4" style="display:none" id="sn_alert_popID">'+mess+'<span id="close-style-box">X</span></div>');

        if (navigator.userAgent.indexOf('MSIE 6.0')!= -1){
        //$('#sn_alert_popID').css("margin-left",'-300px');
        $('#sn_alert_popID').css("position","absolute");
      	$('#sn_alert_popID').css("left",'1200px');
      	$('#sn_alert_popID').css("top",'350px');
      }else{
       	$('#sn_alert_popID').css("position","fixed");
        $('#sn_alert_popID').css("left",'130%');
        $('#sn_alert_popID').css("top",('-10%'));
     }  
	$('#sn_alert_popID').fadeIn('slow');
	$('#close-style-box').click(function(){$('#sn_alert_popID').remove();});

}

var sendAlertAtCursorContacts = function(mess){
	$(".sn_alert_pop").remove();
	$(".sn_alert_pop2").remove();
	//alert(xPos+" "+yPos);
	$('#sn_wrap').before('<div class="sn_alert_pop4" style="display:none" id="sn_alert_popID">'+mess+'<span id="close-style-box">X</span></div>');

	$('#sn_alert_popID').css("position","absolute");
	//alert("x- pos :: "+xPos+"  pop width:: "+$('#sn_alert_popID').width()+"  y- pos :: "+yPos+" [pop height "+$('#sn_alert_popID').height() );
	$('#sn_alert_popID').css("left",1200);
	$('#sn_alert_popID').css("top",(650));
	
	$('#sn_alert_popID').fadeIn('slow');
	$('#close-style-box').click(function(){$('#sn_alert_popID').remove();});

}

var toolTipper = function() {
	$('#nav-funct a').ToolTip(
		{
			className: 'linksTooltip',
			position: 'mouse',
			delay: 300,
			fixPNG: true,
			opacity: .8
			
		}
	);
	$('input').ToolTip(
		{
			className: 'linksTooltip',
			position: 'bottom'
		}
	);
};
var initialEffects = function(){
	$('#select-style').bind(
				'click',
				function()
				{
					if($('#style-box').css('display') =='none'){
							//$('#style-box').animate({height:'toggle' ,opacity:'show'},400);
						//	$('#style-box').show('400',function(){return false;}	);
						$('div#style-box').BlindDown('500', function(){return false;});
							
							// $('#inside-style-box').css('opacity','1.0');
						}
				}
			);
	$('#close-style-box').bind('click',
					function(){
						$('div#style-box').BlindUp('450', {easing:'height'});
					}
 				);
	$('h2#save-style').bind('click',
					function(){
						$('#style-box').TransferTo({to:'select-style', className:'transferer2', duration: 400}).hide();
						}
					);
	
	$('div#inside-style-box').Selectable(
			{
				accept : 'styleswitch',
				opacity : 0.2,
				selectedclass : 'selected',
				helperclass : 'selecthelper'
			}			
		);
	$('a.styleswitch').click(
		function(){
			var thisSelect = $(this);
			alert(thisSelect.attr('href'));
			return false;
			}
		)
		
	
	//form styling
	$('input:[@type=file]').css('border', '1px #ccc solid').css('background','#ccc');

	//news roll
	function newsRoll(){
		var headline_count;
	    var headline_interval;
	    var old_headline = 0;
	    var current_headline = 0;
	  headline_count = $("div.headline").size();
	  $("div.headline:eq("+current_headline+")").css('top', '5px');

	  headline_interval = setInterval(headline_rotate,5000);
	  $('#scrollup').hover(function() {
	    clearInterval(headline_interval);
	  }, function() {
	    headline_interval = setInterval(headline_rotate,5000);
	    headline_rotate();
	  });
	}
	//stylize input elements
	$("input:checkbox/..").click(function(){$(this).animate({background: 'toggle', background:'show'}, 'slow')});
}

//headline scroll
function enableHeadline(){
	var headline_count;
    var headline_interval;
    var old_headline = 0;
    var current_headline = 0;
  headline_count = $("div.headline").size();
  $("div.headline:eq("+current_headline+")").css('top', '5px');

  headline_interval = setInterval(headline_rotate,5000);
  $('#scrollup').hover(function() {
    clearInterval(headline_interval);
  }, function() {
    headline_interval = setInterval(headline_rotate,5000);
    headline_rotate();
  });
}
function headline_rotate() {
  current_headline = (old_headline + 1) % headline_count;
  $("div.headline:eq(" + old_headline + ")")
    .animate({top: -205},"slow", function() {
      $(this).css('top', '150px');
    });
  $("div.headline:eq(" + current_headline + ")")
    .animate({top: 5},"slow"); 
  old_headline = current_headline;
}

// Carousel
jQuery.fn.extend({
    jcarousel: function(o) {
        return this.each(function() {
            new jQuery.jcarousel(this, o);
        });
    }
});

jQuery.extend({
    jcarousel: function(e, o) {
        // Public api of the jCarousel object passed to the
        // handler callback functions.
        var publ = this;

        /**
         * Returns the scope of the carousel which is the outer
         * <div> element containing the required markup (<ul> list,
         * prev/next buttons etc.).
         *
         * @name scope
         * @type Element
         * @cat jCarousel
         */
        publ.scope = function() { return priv.scope; };

        /**
         * Returns the list.
         *
         * @name list
         * @type Element
         * @cat jCarousel
         */
        publ.list = function() { return priv.list; };

        /**
         * Returns the number of elements of the list.
         *
         * @name size
         * @type Number
         * @cat jCarousel
         */
        publ.size = function() { return priv.size; };

        /**
         * (Re)initialises the carousel.
         *
         * @name init
         * @type undefined
         * @param Hash o A set of key/value pairs to set as configuration properties.
         * @cat jCarousel
         */
        publ.init = function(o) { return priv.init(o); };

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number idx The index of the element.
         * @cat jCarousel
         */
        publ.get = function(idx) { return priv.get(idx); };

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number idx The index of the element.
         * @param String html The innerHTML of the element.
         * @cat jCarousel
         */
        publ.add = function(idx, html) { return priv.add(idx, html); };

        /**
         * Returns true if all elements in the given range already exist,
         * false otherwise.
         *
         * @name available
         * @type Boolean
         * @param Number first The first index of the element range.
         * @param Number last The last index of the element range.
         * @cat jCarousel
         */
        publ.available = function(first, last) { return last == undefined ? priv.end >= first : priv.end >= last; };

        /**
         * Notifies the carousel object that updating of the carousel elements
         * has been finished. Must be called from the loadItemHandler callback
         * function after adding items with publ.add().
         *
         * @name loaded
         * @type undefined
         * @cat jCarousel
         */
        publ.loaded = function() { priv.loaded(); };

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat jCarousel
         */
        publ.next = function() { priv.next(); };

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat jCarousel
         */
        publ.prev = function() { priv.prev(); };

        /**
         * Moves the carousel to a certain position.
         *
         * @name next
         * @type undefined
         * @param Number i The index of the element to scoll to.
         * @cat jCarousel
         */
        publ.scroll = function(i) { if (publ.available(i)) { priv.scroll(i); } };

        // Private methods/variables
        var priv = {
            o: {
                orientation: "horizontal",
                itemStart: 1,
                itemVisible: 3,
                itemScroll: null,
                scrollAnimation: "fast",
                autoScroll: 0,
                autoScrollStopOnInteract: true,
                autoScrollStopOnMouseover: false,
                autoScrollResumeOnMouseout: false,
                wrap: false,
                wrapPrev: false,
                itemWidth: null,
                itemHeight: null,
                loadItemHandler: null,
                nextButtonStateHandler: null,
                prevButtonStateHandler: null,
                itemFirstInHandler: null,
                itemFirstOutHandler: null,
                itemLastInHandler: null,
                itemLastOutHandler: null,
                itemVisibleInHandler: null,
                itemVisibleOutHandler: null,
                noButtons: false,
                buttonNextHTML: '<button type="button">&gt;&gt;</button>',
                buttonPrevHTML: '<button type="button">&lt;&lt;</button>'
            },

            scope: null,
            list: null,
            horiz: true,
            top: 0,
            left: 0,
            size: 0,
            end: 0,
            first: 0,
            prevFirst: 0,
            last: 0,
            prevLast: 0,
            inAnimation: false,
            autoTimer: null,
            nextClick: function() { priv.next(); },
            prevClick: function() { priv.prev(); },
            itemFormat: {
                "float":      "left",
                "styleFloat": "left",
                "overflow":   "hidden",
                "listStyle":  "none"
            },

            options: function(o) {
                if (o)
                    jQuery.extend(priv.o, o);

                priv.o.itemStart = Math.max(1, priv.intval(priv.o.itemStart));
                priv.o.itemScroll = priv.o.itemScroll || priv.o.itemVisible;

                if (priv.o.itemWidth)
                    priv.itemFormat.width  = priv.o.itemWidth + "px";

                if (priv.o.itemHeight)
                     priv.itemFormat.height = priv.o.itemHeight + "px";

                priv.horiz = priv.o.orientation == "vertical" ? false : true;
            },

            init: function(o) {
                priv.options(o);

                if (priv.size == 0) {
                    var dummy = priv.format(document.createElement("li"), 1).get(0);
                    priv.list.appendChild(dummy);
                }

                var i = jQuery("li", priv.list).get(0);

                var itemWidth  = i.offsetWidth + priv.margin(i, "marginLeft") + priv.margin(i, "marginRight");
                var itemHeight = i.offsetHeight + priv.margin(i, "marginTop") + priv.margin(i, "marginBottom");

                if (priv.horiz) {
                    priv.dimension = itemWidth;
                    var clipW  = itemWidth * priv.o.itemVisible - priv.margin(i, "marginRight");
                    var clipH  = itemHeight;
                } else {
                    priv.dimension = itemHeight;
                    var clipW  = itemWidth;
                    var clipH  = itemHeight * priv.o.itemVisible - priv.margin(i, "marginBottom");
                }

                jQuery(".jcarousel-clip", priv.scope).css({
                    "zIndex": "2",
                    "padding": 0,
                    "margin": 0,
                    "width":  clipW + "px",
                    "height": clipH + "px",
                    "overflow": "hidden",
                    "position": "relative"
                });

                if (dummy != undefined)
                    priv.list.removeChild(dummy);

                priv.resize();
            },

            prepare: function(e, o) {
                priv.options(o);

                if (e.nodeName == "UL" || e.nodeName == "OL") {
                    priv.list = e;
                    var scope = jQuery(priv.list).parent().get(0);

                    if (jQuery.className.has(scope.className, "jcarousel-clip")) {
                        if (!jQuery.className.has(jQuery(scope).parent().get(0).className, "jcarousel-scope"))
                            scope = jQuery(scope).wrap('<div class="jcarousel-scope"></div>');

                        scope = jQuery(scope).parent().get(0);
                    } else if (!jQuery.className.has(scope.className, "jcarousel-scope"))
                        scope = jQuery(priv.list).wrap('<div class="jcarousel-scope"></div>').parent().get(0);

                    priv.scope = scope;
                } else {
                    priv.scope = e;
                    priv.list = jQuery("ul", priv.scope).get(0) || jQuery("ol", priv.scope).get(0);
                }

                priv.size = priv.end = jQuery("li", priv.list).size();

                if (priv.size > 0) {
                    var idx = 1;
                    jQuery("li", priv.list).each(function() { priv.format(this, idx++); });
                }

                if (!jQuery.className.has(jQuery(priv.list).parent().get(0).className, "jcarousel-clip"))
                    jQuery(priv.list).wrap('<div class="jcarousel-clip"></div>');

                if (!priv.o.noButtons) {
                    if (jQuery(".jcarousel-prev", priv.scope).size() == 0) {
                        var dummy = jQuery(document.createElement("div")).html(priv.o.buttonPrevHTML).get(0);
                        jQuery(".jcarousel-clip", priv.scope).before(jQuery(dummy.firstChild).addClass("jcarousel-prev"));
                    }

                    if (jQuery(".jcarousel-next", priv.scope).size() == 0) {
                        var dummy = jQuery(document.createElement("div")).html(priv.o.buttonNextHTML).get(0);
                        jQuery(".jcarousel-clip", priv.scope).before(jQuery(dummy.firstChild).addClass("jcarousel-next"));
                    }

                    jQuery(".jcarousel-prev", priv.scope).css({"zIndex": "3"});
                    jQuery(".jcarousel-next", priv.scope).css({"zIndex": "3"});
                }

                if (priv.o.autoScrollStopOnMouseover) {
                    if (priv.o.autoScrollResumeOnMouseout) {
                        jQuery(".jcarousel-clip", priv.scope).bind("mouseover", function() { priv.stopAuto(); }).bind("mouseout", function() { priv.startAuto(); });
                    } else {
                        jQuery(".jcarousel-clip", priv.scope).bind("mouseover", function() { priv.disableAuto(); });
                    }
                }

                priv.top  = 0; //priv.intval(jQuery(priv.list).css("top"));
                priv.left = 0; //priv.intval(jQuery(priv.list).css("left"));

                jQuery(priv.list).css({
                    "zIndex": "1",
                    "position": "relative",
                    "top": priv.top + "px",
                    "left": priv.left + "px",
                    "margin": 0,
                    "padding": 0
                }).addClass("jcarousel-list");

                jQuery(priv.scope).addClass("jcarousel-scope").show().find(":hidden").show();
            },

            get: function(idx) {
                return jQuery(".jcarousel-item-" + idx, priv.list);
            },

            add: function(idx, s) {
                var item = priv.get(idx);

                if (item.size() == 0) {
                    var item = priv.format(document.createElement("li"), idx);
                    jQuery(priv.list).append(item);
                    priv.size++;

                    if (priv.size > priv.end)
                        priv.end = priv.size;

                    priv.resize();
                }

                return item.html(s);
            },

            available: function(first, last) {
                if (priv.end >= last)
                    return true;

                priv.end = last;
                return false;
            },

            load: function(first, last) {
                if (priv.o.loadItemHandler == null)
                    return priv.loaded();

                priv.buttons(false, false);
                priv.o.loadItemHandler(publ, first, last, priv.available(first, last));
            },

            loaded: function() {
                if (priv.first > 1 && priv.last < priv.size) {
                    priv.buttons(true, true);
                } else if (priv.first == 1 && priv.last < priv.size) {
                    priv.buttons(true, priv.o.wrapPrev);
                } else if (priv.first > 1 && priv.last >= priv.size) {
                    priv.buttons(priv.o.wrap, true);
                }
            },

            next: function() {
                priv.stopAuto();

                if (priv.o.autoScrollStopOnInteract)
                    priv.disableAuto();

                priv.doNext();
            },

            doNext: function() {
                priv.scroll((priv.o.wrap && priv.last == priv.size) ? 1 : priv.first + priv.o.itemScroll);

                if (priv.o.wrap || priv.last < priv.size)
                    priv.startAuto();
            },

            prev: function() {
                priv.stopAuto();

                if (priv.o.autoScrollStopOnInteract)
                    priv.disableAuto();

                priv.doPrev();
            },

            doPrev: function() {
                priv.scroll((priv.o.wrapPrev && priv.first == 1) ? priv.size - priv.o.itemVisible + 1 : priv.first - priv.o.itemScroll);
                priv.startAuto();
            },

            scroll: function(idx) {
                if (priv.inAnimation)
                    return;

                priv.inAnimation = false;

                priv.prevFirst = priv.first;
                priv.prevLast  = priv.last;

                idx = idx < 1 ? 1 : idx;

                var last = idx + priv.o.itemVisible - 1;
                last = (last > priv.size) ? priv.size : last;

                var first = last - priv.o.itemVisible + 1;
                first = (first < 1) ? 1 : first;

                last = first + priv.o.itemVisible - 1;

                priv.first = first;
                priv.last  = last;

                priv.animate();
            },

            animate: function() {
                var pos = priv.dimension * (priv.first - 1) * -1;

                priv.notify(priv.prevFirst, priv.prevLast, priv.first, priv.last, "onBeforeAnimation");

                if (priv.o.scrollAnimation) {
                    priv.inAnimation = true;
                    jQuery(priv.list).animate(priv.horiz ? {"left": pos} : {"top": pos}, priv.o.scrollAnimation, function() { priv.scrolled(); });
                } else {
                    jQuery(priv.list).css(priv.horiz ? "left" : "top", pos + "px");
                    priv.scrolled();
                }
            },

            scrolled: function() {
                if (priv.first == 1)
                    jQuery(priv.list).css("top", priv.top + "px").css("left", priv.left + "px");

                priv.inAnimation = false;
                priv.notify(priv.prevFirst, priv.prevLast, priv.first, priv.last, "onAfterAnimation");
                priv.load(priv.last + 1, priv.last + priv.o.itemScroll);
            },

            handler: function(handler, evt, state, i1, i2, i3, i4) {
                if (priv.o[handler] == undefined || (typeof priv.o[handler] != 'object' && evt != "onAfterAnimation"))
                    return;

                var handler = typeof priv.o[handler] == 'object' ? priv.o[handler][evt] : priv.o[handler];

                if (typeof handler != 'function')
                    return;

                if (i2 == undefined) {
                    priv.get(i1).each(function() { handler(publ, this, i1, state); });
                    return;
                }

                for (var i = i1; i <= i2; i++) {
                    if (!(i >= i3 && i <= i4))
                        priv.get(i).each(function() { handler(publ, this, i, state); });
                }
            },

            notify: function(prevFirst, prevLast, first, last, evt) {
                var state = prevFirst == 0 ? "init" : (prevFirst < first ? "next" : "prev");

                if (prevFirst != first) {
                    priv.handler("itemFirstOutHandler", evt, state, prevFirst);
                    priv.handler("itemFirstInHandler", evt, state, first);
                }

                if (prevLast != last) {
                    priv.handler("itemLastOutHandler", evt, state, prevLast);

                    priv.handler("itemLastInHandler", evt, state, last);
                }

                priv.handler("itemVisibleInHandler", evt, state, first, last, prevFirst, prevLast);
                priv.handler("itemVisibleOutHandler", evt, state, prevFirst, prevLast, first, last);
            },

            buttons: function(next, prev) {
                if (priv.o.noButtons)
                    return;

                jQuery(".jcarousel-next", priv.scope)[next ? "bind" : "unbind"]("click", priv.nextClick)[next ? "removeClass" : "addClass"]("jcarousel-next-disabled")[next ? "removeAttr" : "attr"]("disabled", true);
                jQuery(".jcarousel-prev", priv.scope)[prev ? "bind" : "unbind"]("click", priv.prevClick)[prev ? "removeClass" : "addClass"]("jcarousel-prev-disabled")[prev ? "removeAttr" : "attr"]("disabled", true);

                if (priv.o.nextButtonStateHandler != null)
                    jQuery(".jcarousel-next", priv.scope).each(function() { priv.o.nextButtonStateHandler(publ, this, next); });

                if (priv.o.prevButtonStateHandler != null)
                    jQuery(".jcarousel-prev", priv.scope).each(function() { priv.o.prevButtonStateHandler(publ, this, prev); });
            },

            startAuto: function() {
                if (priv.o.autoScroll > 0)
                    priv.autoTimer = setTimeout(function() { priv.doNext(); }, priv.o.autoScroll * 1000);
            },

            stopAuto: function() {
                if (priv.autoTimer == null)
                    return;

                clearTimeout(priv.autoTimer);
                priv.autoTimer = null;
            },

            disableAuto: function() {
                priv.stopAuto();
                priv.o.autoScroll = 0;
            },

            resize: function() {
                if (priv.size == 0)
                    return;

                if (priv.horiz)
                    jQuery(priv.list).css("width", priv.size * priv.dimension + 100 + "px");
                else
                    jQuery(priv.list).css("height", priv.size * priv.dimension + 100 + "px");
            },

            format: function(item, idx) {
                return jQuery(item).css(priv.itemFormat).addClass("jcarousel-item-" + idx);
            },

            margin: function(e, p) {
                if (p == "marginRight" && jQuery.browser.safari) {
                    var old = {"display": "block", "float": "none", "width": "auto"}, oWidth, oWidth2;

                    jQuery.swap(e, old, function() { oWidth = e.offsetWidth; });

                    old["marginRight"] = 0;
                    jQuery.swap(e, old, function() { oWidth2 = e.offsetWidth; });

                    return oWidth2 - oWidth;
                }

                return priv.intval(jQuery.css(e, p));
            },

            intval: function(v) {
                v = parseInt(v);
                return isNaN(v) ? 0 : v;
            }
        };

        // Initialize the carousel
        priv.prepare(e, o);
        priv.init();
        priv.buttons(false, false);
        priv.load(1, priv.o.itemStart + priv.o.itemVisible);
        priv.scroll(priv.o.itemStart);
        priv.startAuto();
    }
});

// Character counter
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings);
	 */
(function($) {
		/**
		 * attaches a character counter to each textarea element in the jQuery object
		 * usage: $("#myTextArea").charCounter(max, settings);
		 */

		$.fn.charCounter = function(max, settings) {
			max = max || 100;
			settings = $.extend({
				container: "<em>",
				classname: "sn_charcount",
				format: "(%1 characters remaining)",
				pulse: true
			}, settings);
			var p;

			function count(el, container) {
				el = $(el);
				if (el.val().length > max) {
				    el.val(el.val().substring(0, max));
				    if (settings.pulse && !p) {
				    	pulse(container, true);
				    };
				};
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			};

			function pulse(el, again) {
				if (p) {
					window.clearTimeout(p);
					p = null;
				};
				el.animate({ opacity: 0.1 }, 100, function() {
					$(this).animate({ opacity: 1.0 }, 100);
				});
				if (again) {
					p = window.setTimeout(function() { pulse(el) }, 200);
				};
			};

			return this.each(function() {
				var container = (!settings.container.match(/^<.+>$/)) 
					? $(settings.container) 
					: $(settings.container)
						.insertAfter(this)
						.addClass(settings.classname);
				$(this)
					.bind("keydown", function() { count(this, container); })
					.bind("keypress", function() { count(this, container); })
					.bind("keyup", function() { count(this, container); })
					.bind("focus", function() { count(this, container); })
					.bind("mouseover", function() { count(this, container); })
					.bind("mouseout", function() { count(this, container); })
					.bind("paste", function() { 
						var me = this;
						setTimeout(function() { count(me, container); }, 10);
					});
				if (this.addEventListener) {
					this.addEventListener('input', function() { count(this, container); }, false);
				};
				count(this, container);
			});
		};

	})(jQuery);



function switchStylestyle(styleName)
{
	// $('link[@title=Master-CSS]').html("blah blah blh");
	$('link[@title=alt-CSS]').attr({href: "css/skins/"+styleName+".css"});
	// $('link[@rel*=style][@title]').each(function(i) 
	// 			{
	// 				this.disabled = true;
	// 				if ($(this).attr("title") == styleName) {
	// 					//this.disabled = false;
	// 					}
	// 				//else{this.disabled = false;}
	// 			});
	// 			createCookie('style', styleName, 365);
}

// Star ratings: Click on a star, returns a rating number
var starRating = function() {
	var ratingAvg = "";
	var newWidth = (ratingAvg * 15) + 1;
//	$('li.current-rating').css({width: "65px", background-color:"#000"});
	$('ul.star-rating li a').click(
			function(){
				alert ($(this).attr("class")); 
				$('rating-wrap').html("You rated this "+$(this).attr("class")+" out of 5")
				.fadeIn("slow")
				.animate({opacity: 1.0}, 2000).fadeOut("slow");
				return $(this).attr("class");
				}
		);
};

jQuery.fn.toggleCheckboxes = function(ignore)
{
	ignore = ignore || [];
	return this.each(
		function()
		{
			jQuery("input[@type=checkbox]", this).not(ignore).each(
				function()
				{
					this.checked = !this.checked;
				}
			)
		}
	)
}
jQuery.fn.checkCheckboxes = function(ignore)
{
	ignore = ignore || [];
	return this.each(
		function()
		{
			jQuery("input[@type=checkbox]", this).not(ignore).each(
				function()
				{
					this.checked = true;
				}
			)
		}
	)
}
jQuery.fn.unCheckCheckboxes = function(ignore)
{
	ignore = ignore || [];
	return this.each(
		function()
		{
			jQuery("input[@type=checkbox]", this).not(ignore).each(
				function()
				{
					this.checked = false;
				}
			)
		}
	)
}
// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name,"",-1);
}
// /cookie functions
//ajax file uploader
jQuery.extend({

	createUploadIframe: function(id, uri)
	{
			//create frame
			var frameId = 'jUploadFrame' + id;
			
			if(window.ActiveXObject) {
				var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
				if(typeof uri== 'boolean'){
					io.src = 'javascript:false';
				}
				else if(typeof uri== 'string'){
					io.src = uri;
				}
			}
			else {
				var io = document.createElement('iframe');
				io.id = frameId;
				io.name = frameId;
			}
			io.style.position = 'absolute';
			io.style.top = '-1200px';
			io.style.left = '-1200px';

			document.body.appendChild(io);

			return io			
	},
	createUploadForm: function(id, fileElementId,data)
	{
		//create form
		var inputVariables='';	
		if(data)
		{
			var postVariables=data.split('&');
			
			for(var i=0;i<postVariables.length;i++)
			{
				var variables=postVariables[i].split('=');
				inputVariables+='<input type="text" name="'+variables[0]+'" value="'+unescape(variables[1])+'"/>';
			}	
		}
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form	 action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data">'+inputVariables+'</form>'); 
		var oldElement = $('#' + fileElementId);
		var newElement = $(oldElement).clone();

		
		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);
		//set attributes
		$(form).css('position', 'absolute');
		$(form).css('top', '-1000px');
		$(form).css('left', '-1000px');
		$(form).appendTo('body');
		return form;
	},

	ajaxFileUpload: function(s) {
		// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
		s = jQuery.extend({}, jQuery.ajaxSettings, s);
		var id = new Date().getTime()		 
		var form = jQuery.createUploadForm(id, s.fileElementId,s.data);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var triggerErrors=true;
		if(typeof(s.triggerErrors)=='boolean')
		{
			triggerErrors=s.triggerErrors;
		}
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
		// Watch for a new set of requests
		if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}			 
		var requestDone = false;
		// Create the request object
		var xml = {}   
		if ( s.global )
			jQuery.event.trigger("ajaxSend", [xml, s]);
		// Wait for a response to come back
		var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
			try 
			{				
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
					 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
					xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
			}catch(e)
			{
				if(triggerErrors)
				{
					jQuery.handleError(s, xml, null, e);
				}
			}
			if ( xml || isTimeout == "timeout") 
			{				
				requestDone = true;
				var status;
				try {
					status = isTimeout != "timeout" ? "success" : "error";
					// Make sure that the request was successful or notmodified
					if ( status != "error" )
					{
						// process the data (runs the xml through httpData regardless of callback)
						var data = jQuery.uploadHttpData( xml, s.dataType );	
						// If a local callback was specified, fire it and pass it the data
						if ( s.success )
							s.success( data, status );
	
						// Fire the global callback
						if( s.global )
							jQuery.event.trigger( "ajaxSuccess", [xml, s] );
					} else
						jQuery.handleError(s, xml, status);
				} catch(e) 
				{
					
					if(triggerErrors)
					{
						status = "error";
						jQuery.handleError(s, xml, status, e);
					}
				}

				// The request was completed
				if( s.global )
					jQuery.event.trigger( "ajaxComplete", [xml, s] );

				// Handle the global AJAX counter
				if ( s.global && ! --jQuery.active )
					jQuery.event.trigger( "ajaxStop" );

				// Process result
				if ( s.complete )
					s.complete(xml, status);

				jQuery(io).unbind()

				setTimeout(function()
									{	try 
										{
											$(io).remove();
											$(form).remove();	
											
										} catch(e) 
										{
											if(triggerErrors)
											{
												jQuery.handleError(s, xml, null, e);
											}
										}									

									}, 100)

				xml = null

			}
		}
		// Timeout checker
		if ( s.timeout > 0 ) 
		{
			setTimeout(function(){
				// Check to see if the request is still happening
				if( !requestDone ) uploadCallback( "timeout" );
			}, s.timeout);
		}
		try 
		{
		   // var io = $('#' + frameId);
			var form = $('#' + formId);
			$(form).attr('action', s.url);
			$(form).attr('method', 'POST');
			$(form).attr('target', frameId);
			if(form.encoding)
			{
				form.encoding = 'multipart/form-data';				
			}
			else
			{				
				form.enctype = 'multipart/form-data';
			}			
			$(form).submit();

		} catch(e) 
		{	
			if(triggerErrors)
			{		
				jQuery.handleError(s, xml, null, e);
			}
		}
		if(window.attachEvent){
			document.getElementById(frameId).attachEvent('onload', uploadCallback);
		}
		else{
			document.getElementById(frameId).addEventListener('load', uploadCallback, false);
		}		
		return {abort: function () {}}; 

	},

	uploadHttpData: function( r, type ) {
		var data = !type;
		data = type == "xml" || data ? r.responseXML : r.responseText;
		// If the type is "script", eval it in global context
		if(type=='text')
		{
			data=data.replace(/&amp;/g,'&');
		}
		if ( type == "script" )
			jQuery.globalEval( data );
		// Get the JavaScript object, if JSON is used.
		if ( type == "json" )
			eval( "data = " + data );
		// evaluate scripts within html
		if ( type == "html" )
			jQuery("<div>").html(data).evalScripts();
			//alert($('param', data).each(function(){alert($(this).attr('value'));}));
		return data;
	}
})
