/**
 * This file extends the jquery library with custom funcitons relevant to the red5 base cms.
 * The function is encapsulated so that you can use the $ reference for jquery without conflict
 * with other libraries. More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
 */

(function($){
    $.fn.extend({
		/**
		 * ADMIN
		 * accordianAdmin: this is ths accordian for the red5 admin section
		 */
        accordianAdmin: function(settings)
		{
			var s = $.extend({
				openicn: '/media/pics/cms/icn-expand.png',  // icon when the accordian is open
				closeicn: '/media/pics/cms/icn-collapse.png'  // icon when the accordian is closed
            }, settings);
			
			$(this).click(function(){
				var accordianhead = $(this);
				var accordianimg = accordianhead.find('img').eq(0);
				var openicn = s.openicn;
				var closeicn = s.closeicn;
				var accNext = accordianhead.next();
				
				if (accNext.css('display') == 'none') {
					accordianhead.next().show();
				}
				else {
					accordianhead.next().hide();
				}
	
				if(accordianimg.attr('src') == openicn){
					accordianimg.attr('src',closeicn);
				} else {
					accordianimg.attr('src',openicn);
				}
	
			});
		},
		/**
		 * ADMIN
		 * accordianBanner: custom accordian function for the banner panel of the admin section
		 */
        accordianBanner: function(settings)
        {
            var s = $.extend({
                openIndicator: '+',	 //indicator for an open panel
                closeIndicator: '-',  //indicator for a closed panel
                showText: 'Show All',  //text for the show all link
                hideText: 'Hide All',  //text for the hide all link
                tableheadclass: 'itemheaderrow',  //class for the header of the table (where the toggle all link goes)
                rowheadclass: 'accordianHeader',  //class for the header row for the toggle
                indicatorclass: 'indicator',  //class for the toggle indicator
                toggleallclass: 'toggleAll'  //class for the taggle all link
            }, settings);
            
            var thistable = $(this);
            var headerrow = thistable.find('.' + s.tableheadclass);
            var targetall = headerrow.eq(0).nextAll('tr').not('.' + s.rowheadclass);
            
            $('.' + s.rowheadclass).click(function(){
                var thisheader = $(this);
                var thisindicator = thisheader.find('.' + s.indicatorclass);
                
                thisheader.nextAll('tr').not(thisheader.nextAll('tr.' + s.rowheadclass).eq(0).nextAll('tr').andSelf()).toggle();
                
                if (thisindicator.html() == s.closeIndicator) {
                    thisindicator.html(s.openIndicator);
                }
                else {
                    thisindicator.html(s.closeIndicator);
                }
                return false;
            }).find('th').prepend($(document.createElement('span')).addClass(s.indicatorclass).css('float', 'right').html(s.openIndicator));
            
            headerrow.find('td').prepend($(document.createElement('span')).addClass(s.toggleallclass).css('float', 'right').css('cursor', 'pointer').html(s.showText));
            
            targetall.hide();
            
            $('.' + s.toggleallclass).toggle(function(){
                targetall.show();
                $(this).html(s.hideText);
            }, function(){
                targetall.hide();
                $(this).html(s.showText);
            });
        },
		/**
		 * FRONT END
		 * This is the ajax functionality for the related select browse products widget,
		 * which will repopulate the dropdowns based on the selections. Because these 
		 * dropdowns are highly dependent on javascript, its reccommended that you set
		 * autocomplete="off" in the attributes, to stop firefox "remembering" the form 
		 * values on a soft reload. 
		 */
        ajaxBrowse: function(settings)
		{
            var s = $.extend({
				slideSpeed: 400,  //The transition speed of the slide animation
				hideInactive: true,  //Hide the dropdowns that return no records
				loadingImg: '/media/pics/site/ajax-loader.gif' // image to replace the submit button while loading
            }, settings);
            
            var thisForm = $(this);
            var selects = thisForm.find('select');
			var btnImg = thisForm.find(':submit').css('background');
			/**
			 * the function to diable the form while the ajax is loading
			 */
            var disable = function(){
                selects.attr('disabled', true);
                thisForm.submit(function(){
                    return false;
                }).find(':submit').css('background','transparent url("'+s.loadingImg+'") no-repeat top right');
            };
			/**
			 * the function to enable the form when the ajax has finished loading
			 */
            var enable = function(){
                selects.removeAttr('disabled');
                thisForm.unbind('submit').find(':submit').css('background',btnImg);
            };
			
            selects.change(function(){
                var formInfo = thisForm.parseForm();
                var thisSelect = '';
                if ($(this).val() !== 0) {
                    thisSelect = $(this);
                }
                if ($.AjaxCFC) {
                    disable();
                    $.AjaxCFC({
                        url: "/org/red5/ajax/productFinder.cfc",
                        method: thisForm.attr('rel'),
                        data: ({
                            'formData': formInfo
                        }),
                        blockUI: false,
                        success: function(r){
							if (r) {
								selects.not(thisSelect).each(function(){
									var d = eval('r.' + $(this).attr('name'));
									var a = d.data.value;
									$(this).html(function(){
										var r = '';
										for (i = 0; i < a.length; i++) {
											r += '<option value="' + d.data.value[i] + '">' + d.data.label[i] + '</option>';
										}
										return r;
									}());
									/**
									 * Only show the selects if there is somthing to filter on.
									 * need to show and hide the parent due to the markup used.
									 */
									if (s.hideInactive) {
										if (a.length == 1) {
											$(this).parent().slideUp(s.slideSpeed);
										}
										else {
											$(this).parent().slideDown(s.slideSpeed);
										}
									}
								});
							}
							enable();
                        }
                    });
                }
            });
            
        },
		/**
		 * FRONT END
		 * ajaxCaro: this function works with the accordian.cfc to return carousel content 
		 * via ajax, and repopulate the markup. The container to hold this widget should have 
		 * position relative and the articles should have a position absolute to transition
		 * correctly. The container to hold the widget should also have fixed width and height 
		 * to ensure the timer events execute correctly.
		 */
        ajaxCaro: function(settings)
        {
            var s = $.extend({
                nextClass: 'next', // class for the next trigger
                prevClass: 'prev',  // class for the previous trigger
                controlsClass: 'controls', // class the the container for the controls
				imgClass: 'articleImg', // class to target the img src you want changed 
				titleClass: 'articleTitle', // class to target the title data
				linkClass: 'articleLink', // class to target the herf link
				bodyClass: 'articleBody', // class to target the body text
				containerClass: 'articleObj', // class of the container to duplicate
				containerHolder: 'ajaxCaro', // class that holder the article object
				loadingClass: 'loading', // class of the loding info
                delay: 7000, // speed for the image transition
				hideControls: true  // controls side up on hover
            }, settings);

            var thisContainer = $(this);
            
            /**
			 * You must setup the variable for the timer event before you assign the timer 
			 * else the clearInterval function will not work correctly
			 */
			var setTimer;
			
			setTimer = setInterval(function(){
				changeContent('next', 'false');
			}, s.delay);
            
			thisContainer.hover(function(){ //over
				if (s.hideControls) {
					thisContainer.find('.' + s.controlsClass).show();
				}
				clearInterval(setTimer);
			}, function(){ //out
				if (s.hideControls) {
					thisContainer.find('.' + s.controlsClass).hide();
				}
				setTimer = setInterval(function(){
					changeContent('next', 'false');
				}, s.delay);
			});
			/**
			 * Moved assign controls into a function so that the controls can 
			 * be part of the article object.
			 */
			var assignControls = function(){
				thisContainer.find('.' + s.prevClass).unbind('click').click(function(){
					changeContent('prev');
					return false;
				}).end().find('.' + s.nextClass).unbind('click').click(function(){
					changeContent('next');
					return false;
				});
			};
			
			assignControls();
			
			/**
			 * allow variable is to prevent stacking requests
			 */
            var allow = true;
			
            var changeContent = function(mode, load){
                var m = mode || 'next';
                var r = thisContainer.find('.'+s.containerClass).attr('rel');
                var loading = thisContainer.find('.'+s.loadingClass);
                var showLoad = load || 'true';
                if (showLoad == 'true') {
                    loading.fadeIn();
                }
                
                if ($.AjaxCFC && allow) {
					allow = false;
                    $.AjaxCFC({
                        url: "/org/red5/ajax/carousel.cfc",
                        method: 'getItem',
                        data: ({
                            'mode': m,
                            'getRow': r
                        }),
                        blockUI: false,
                        success: function(r){
                            if (r.ERROR === false) {
                                loading.fadeOut();
                                while (thisContainer.find('.'+s.containerClass).length >= 2) {
                                    thisContainer.find('.'+s.containerClass).eq(0).remove();
                                }
								var oldArticleObj = thisContainer.find('.'+s.containerClass).eq(0);
                                var newArticleObj = oldArticleObj.clone().hide();
                                newArticleObj.find('.'+s.imgClass).attr('src', r.IMGSRC);
                                newArticleObj.find('.'+s.titleClass).html(r.TITLE);
                                newArticleObj.find('.'+s.linkClass).attr('href', r.LINK);
                                newArticleObj.find('.'+s.bodyClass).html(r.BODY);
                                newArticleObj.attr('rel', r.CURRENTROW);
                                newArticleObj.appendTo(thisContainer.find('.'+s.containerHolder)).fadeIn('slow').fadeTo('slow', 1);
                                oldArticleObj.fadeTo('slow',0,function(){
									$(this).remove();
								});
								assignControls();
                            }
							allow = true;
                        }
                    });
                } else if (!$.AjaxCFC) {
					alert('this function requires the ajaxCFC plugin to function');
				}
                
            };
            
        },
		/**
		 * ALL
		 * This function works with shadowbox and livequery to provide a simple way to display
		 * ajax content in shadowbox. This allows you to alter the shadowbox calling options on 
		 * a per link basis, for example:
		 *  <a class="ajaxLink" href="/href/" rel="height:300,width:300,title:'shadowBoxTitle',addClass:'extraShadowboxClass'">
		 *      Link
		 *  </a>
		 * These settings allow you to completely restyle shadowbox popus on a per link basis
		 */
		ajaxLink: function(settings)
		{
            var s = $.extend({
                blockMessage: 'Please Wait...', // class for the next trigger
                appOnline: true
            }, settings);

			var thisLink = $(this);
			
			if (!Shadowbox && !$.livequery) {
				alert('The ajaxLink plugin requires Shadowbox and livequery to function');
			} else {
				thisLink.livequery(function(){
					$(this).click(function(){
						var rel = eval('({' + $(this).attr('rel') + '})') || '';
						var link = $(this).attr('href');
						
						if (/\?/.test(link) === true) {
							link = link.replace('?', '?ajax=1&');
						}
						else {
							link += '?ajax=1';
						}
						
						var height = rel.height || 500;
						var width = rel.width || 485;
						var title = rel.title || $(this).attr('title');
						var addclass = rel.addclass || '';
						
						if ($.blockUI) {
							$.blockUI({
								message: '<' + 'img src=\'/media/pics/cms/blockUI-loader.gif\' />&nbsp;&nbsp;' + s.blockMessage,
								fadeIn: 700,
								showOverlay: false,
								centerY: false,
								css: {
									width: '300px',
									top: '10px',
									left: '',
									right: '10px',
									border: 'none',
									padding: '15px 5px',
									backgroundColor: '#000',
									'-webkit-border-radius': '10px',
									'-moz-border-radius': '10px',
									opacity: '.6',
									color: '#fff',
									'z-index': '1000000011'
								}
							});
						}
						
						$.ajax({
							url: function(){
								var ret = link;
								if(!s.appOnline){
									 ret += '&ShowDebug=0';
								}
								return ret;
							}(),
							cache: true,
							success: function(r){
								$('#sb-container').addClass(addclass);
								Shadowbox.open({
									player: 'html',
									content: r,
									height: height,
									width: width,
									title: title
								});
							},
							complete: function(){
								if ($.unblockUI) {
									$.unblockUI({
										fadeOut: 900
									});
								}
							}
						});
						
						return false;
					});
				});
			}
		},
		/**
		 * FRONT END
		 * ajaxTabs: this is a function for the custom ui tabs in my account
		 */
        ajaxTabs: function(settings)
        {
            var s = $.extend({
                not: '.notab',  //exclude items from the tabbed menu
                selectedClass: 'selected',  //define the selected tab class
                loadingimg: '/media/pics/site/ajax-loader.gif'  //the backgound image for the currently loading tab
            }, settings);
            
            var thislist = $(this);
            var links = thislist.find('a').not(s.not);
            var targetDiv = thislist.attr('rel');
            
            links.each(function(){
				/**
				 * This check the last item in the resource path, and checks against 
				 * the link for each tab, so if a user goes directly to a my account page,
				 * the correct tab will be highlighted.
				 */
                var anchor = $(this);
                if (window.location.href.split('/').reverse()[1] == anchor.attr('href').split('/').reverse()[1]) {
                    anchor.parent('li').addClass(s.selectedClass);
                }
            }).click(function(){
				/**
				 * This adds the ajax click handler for each of the tabs so that the content
				 * will be loaded in the correct section.
				 */
                var anchor = $(this);
                var link = anchor.attr('href');
                
				/**
				 * test for a querystring, and insert the ajax=1 variable appropriately
				 */
				if (/\?/.test(link) === true) {
					link = link.replace('?', '?ajax=1&');
				}
				else {
					link += '?ajax=1';
				}
				
                anchor.parent().css({
					'background-image':'url(' + s.loadingimg + ')',
					'background-repeat':'no-repeat',
					'background-position':'1px center'
					});
				
				/**
				 * Beacuse the html of these pages doesn't change, use the jquery ajax 
				 * to load the content and set the chached to true. 
				 */
				$.ajax({
					url: link + '&ShowDebug=0',
					cache: true,
					success: function(r){
						$(targetDiv).html(r);
					},
					complete: function() {
						anchor.parent('li').css('background-image', 'none').addClass(s.selectedClass).siblings().removeClass(s.selectedClass);
					}
				});
                    
                return false;
            });
        },
		/**
		 * ADMIN
		 * bannerPreview: this function depends on the tooltip function.
		 * it creates a popup image preveiew for the banner selects
		 */
        bannerPreview: function(settings)
        {
            var s = $.extend({
                noImageMsg : "No Image Available"  //message when no image is available for hover preview
            }, settings);
			if($.fn.tooltip){
				$(this).each(function(){
		            var thisPreview = $(this);
		            var thisSelect = thisPreview.prev('select');
					var getMarkup = function() {
						var bannerVal = thisSelect.val();
						var bannerOpt = thisSelect.find('option[value='+bannerVal+']');
						var img = bannerOpt.attr('rel');
						var name = bannerOpt.html();
					    if (!img) {
					        return $(document.createElement('span')).html(name+'<'+'br>'+s.noImageMsg);
					    } else {
					        return $(document.createElement('img')).attr('src', '/uploads/' + img);
						}
		            };

					thisPreview.mouseenter(function() {
						thisSelect.focus();
					}).mouseleave(function(){
						thisSelect.blur();
					}).tooltip({
					    delay: 0,
					    showURL: false,
						bodyHandler: function() {
							return getMarkup();
						}
					}).prev('select').keyup(function(){
				        $('#tooltip > .body').html(getMarkup());
					});
				});
			/**
			 * This depends on the jQuery tooltip plugin from bassistance to function.
			 * This is a catch for implementation.
			 */
			} else {
				alert('bannerPreview requires jQuery tooltip (http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/) to function');
			}
		},
		/**
		 * ALL
		 * delay: this function allows you to put a delay on a jquery event
		 * (good for ajax typing checking) this needs an update for settings
		 */
        delay: function(options) 
        {
            var timer;
            var delayImpl = function(eventObj){
                if (timer !== null) {
                    clearTimeout(timer);
                }
                var newFn = function(){
                    options.fn(eventObj);
                };
                timer = setTimeout(newFn, options.delay);
            };
            
            return this.each(function(){
                var obj = $(this);
                obj.bind(options.event, function(eventObj){
                    delayImpl(eventObj);
                });
            });
        },
		/**
		 * ALL
		 * this function makess a message flash twice. Typically used for returning 
		 * ajax messages and ensuring user experience is consistent.
		 */
        flash: function(time)
        {
            var flash = time || 175;  //The length of the trasition for the flash
            $(this).fadeOut(flash).fadeIn(flash).fadeOut(flash).fadeIn(flash);
        },
		/**
		 * FRONT END
		 * this take a container with images previews, and pushes their rel tag 
		 * paths to another container
		 */
        imgRoller: function(settings)
        {
            var s = $.extend({
                target: '.imgTarget',
                targetClass: 'loading'
            }, settings);
            
            var target = $(s.target);
            var thisContainer = $(this);
            var thisImgList = thisContainer.find('img');
            
            thisContainer.addClass(s.targetClass);
            thisImgList.each(function(){
                $(this).hover(function(){ //over
                    /**
                     *  the load event here will not display the image until the browser has 
                     *  loaded it, so you can put a loading gif in the background of the target 
                     *  container if you choose
                     */
                    target.html(
						$(document.createElement('img')).attr('src', $(this).attr('rel')).css('display','none').load(function(){
							$(this).fadeIn();
						})
					);
                }, function(){ //out
                    target.html(
						$(document.createElement('img')).attr('src', target.attr('rel')).css('display','none').load(function(){
							$(this).fadeIn();
						})
					);
                });
            });
            
        },
		/**
		 * ADMIN
		 * navTreeSelect: This requires shadowbox and livequery to function. 
		 * This function works with the nav tree selector to popup the the 
		 * tree in a shadowbox so that you can select a page via the tree 
		 * interface.
		 */
		navTreeSelect: function (settings)
		{
			var	s = jQuery.extend({
				popupTitle : 'Select A Parent',  //Title for the Shadowbox popup
				loadingImg : '/media/pics/site/ajax-loader.gif'  //loading img for the ajax
			}, settings);

			var thisSelect = $(this);
			var thisSelectID = thisSelect.attr('id');
			var thisEditLink = $('#edit'+thisSelectID); 
			var defaultImg = thisEditLink.attr('src');
			var saveclick = false;
			
			if ($.fn.livequery && Shadowbox) {
				var mainFunction = function()
				{
					var sbContainer = $('#sb-container');
					thisEditLink.unbind('click').click(function(){
						thisEditLink.attr('src', s.loadingImg);
						/**
						 * Add a class to style the shadowbox correctly
						 */
						sbContainer.addClass('parentSelect');
						/**
						 * Add the livequery selector to open the correct parent BEFORE
						 * you make the ajax call so that this always fires correctly
						 */
						$('#sb-content > #CFForm_1').expire().livequery(function(){
							var thisForm = $(this);
							var addChildLinks = thisForm.find('tr').slice(1).not('.footerrow').find('.addChild');
							
							addChildLinks.unbind('click').click(function(){
								var ThisID = $(this).attr('href').split('=')[2];
								thisSelect.val(ThisID).focus();
								Shadowbox.close();
								return false;
							});
							
							var thisTr = addChildLinks.filter('[rel=' + thisSelect.val() + ']').parents('tr').eq(0);
							thisTr.css({
								color: 'red',
								cursor: 'pointer'
							}).attr('title', 'Currently Selected Parent');
							
							var thisDepth = thisTr.attr('rel');
							while (thisDepth >= 1) {
								thisDepth = thisDepth - 1;
								thisTr.prevAll('[rel=' + thisDepth + ']').eq(0).find('.parent').click();
							}
						});
						/**
						 * Now the setup has been done, make the ajax call for the drill-down selector
						 */
						$.ajax({
							url: '/admin/admin_content.cfm?treeRoot=-1&Move=1&Popup=1&Ajax=1&ShowDebug=0',
							cache: true,
							success: function(html){
								Shadowbox.open({
									content: html,
									player: 'html',
									title: s.popupTitle,
									width: 700,
									height: 700
								});
							},
							complete: function(){
								thisEditLink.attr('src', defaultImg);
							}
						});
					}).each(function(){
						if (saveclick) {
							$(this).click();
						}
					});
				};
				
				thisEditLink.click(function(){
					thisEditLink.attr('src', s.loadingImg);
					saveclick = true;
					mainFunction();
				});
				
				if (!$('#sb-container').length) {
					$('#sb-container').livequery(function(){
						mainFunction();
					});
				}
				
			} else {
				alert('The navTreeSelect plugin requires livequery (http://docs.jquery.com/Plugins/livequery) and Shadowbox (http://www.shadowbox-js.com/) to function');
			}
		},
		/**
		 * FRONT END
		 * newsSubscribe: this function creates the newsletter widget, with subscribe and 
		 * unsubscribe functionality
		 */
        newsSubscribe: function(settings)
        {
            var s = $.extend({
                submitClass: 'NLSubmit',
                toggleClass: 'NLToggle',
                emailClass: 'NLEmail',
                subscribeFn: 'subscribe',
                unsubscribeFn: 'unsubscribe',
                subscribeTxt: 'Click here to subscribe',
                unsubscribeTxt: 'Click here to unsubscribe',
                defaultTo: 'subscribe',
                toggle: 1
            }, settings);
            
            var thisdiv = $(this);
            
            var d = new Object();
            
            if (s.defaultTo == 'subscribe') {
                d = {
                    txt: s.unsubscribeTxt,
                    fn: s.subscribeFn
                };
            }
            else 
                if (s.defaultTo == 'unsubscribe') {
                    d = {
                        txt: s.subscribeTxt,
                        fn: s.unsubscribeFn
                    };
                }
            
            thisdiv.html(function(){
                var ret = '<' + 'form>' +
                '<' +
                'input rel="' +
                d.fn +
                '" type="text" name="' +
                s.emailClass +
                '" class="' +
                s.emailClass +
                ' jqueryReplace" value="Enter Your Email..." maxlength="100"/>' +
                '<' +
                'span class="' +
                s.submitClass +
                '" style="display:inline-block;">Submit<' +
                '/span>';
                if (s.toggle == 1) {
                    ret += '<' + 'span class="' + s.toggleClass + '">' + d.txt + '<' + '/span>';
                }
                ret += '<' + '/form>';
                return ret;
            }()).attr('class', s.subscribeFn).find('.' + s.toggleClass.replace(/\s+/, '.')).click(function(){
                if (thisdiv.attr('class') == s.subscribeFn) {
                    thisdiv.attr('class', s.unsubscribeFn).find('input[rel="' + s.subscribeFn + '"]').attr('rel', s.unsubscribeFn);
                    submitLink.html('Unsubscribe');
                    submitToggle.html(s.subscribeTxt);
                }
                else {
                    thisdiv.attr('class', s.subscribeFn).find('input[rel="' + s.unsubscribeFn + '"]').attr('rel', s.subscribeFn);
                    submitLink.html('Subscribe');
                    submitToggle.html(s.unsubscribeTxt);
                }
            });
            
            var submitLink = thisdiv.find('.' + s.submitClass.replace(/\s+/, '.'));
            var submitToggle = thisdiv.find('.' + s.toggleClass.replace(/\s+/, '.'));
            var emailInput = thisdiv.find('.' + s.emailClass.replace(/\s+/, '.'));
            var thisForm = thisdiv.find('form');
            
            thisForm.validate({
				/**
				 * using eval here so that these objects are inline with the dynamic settings
				 */
				rules: eval(
					'({' + 
						s.emailClass + ':{' +
							'required:true,' +
							'email:true' +
						'}' +
					'})'
				),
				messages: eval(
					'({' + 
						s.emailClass + ':{' +
							'required:"&nbsp;&nbsp;&nbsp;required",' +
							'email:"&nbsp;&nbsp;&nbsp;invalid email"' +
						'}' +
					'})'
				),
				errorPlacement: function(error, element){
					element.parent().append(error);
				},
                submitHandler: function(){
                    var emailEntered = emailInput.val();
                    var mode = emailInput.attr('rel');

                    $.AjaxCFC({
                        url: "/org/red5/ajax/newsletter.cfc",
                        method: mode,
                        blockUI: true,
                        data: {
                            "email": emailEntered
                        },
                        success: function(r){
                            thisdiv.html(r.TEXT);
                        }
                    });
                }
            });
            
            thisdiv.find('.' + s.submitClass).click(function(){
                thisForm.submit();
            });
            
        },
		/**
		 * ALL
		 * parseForm: this uses the serialize jquery method and builds a JSON object 
		 * to pass to ajaxCFC
		 */
        parseForm: function() 
        {
			var r1 = new RegExp('=');
			var r2 = new RegExp('\&');
            var formData = '({\"';
			
            formData = formData + this.serialize();
			 
            while (r1.test(formData) === true) {
                formData = formData.replace('=', '\"\:\"');
            }
			
            while (r2.test(formData) === true) {
                formData = formData.replace('\&', '\",\"');
            }
			
            formData = formData + '\"})';
			
            return eval(formData);
        },
		/**
		 * ALL
		 * toggleCheckbox: toggle a target div with a checkbox
		 * has two modes, normal and reverse
		 */
        toggleCheckbox: function(settings) 
        {
            var s = $.extend({
                mode: 'normal'
            }, settings);
            
            var togglethis = function(target, checkbox){
				var condition;
                if (s.mode == 'normal') {
                    condition = checkbox.is(':checked');
                }
                else 
                    if (s.mode == 'reverse') {
                        condition = !checkbox.is(':checked');
                    }
                if (condition) {
                    $(target).show();
                }
                else {
                    $(target).hide();
                }
            };
            
            $(this).each(function(){
                var thischeckbox = $(this);
                var thistarget = thischeckbox.attr('rel');
                thischeckbox.click(function(){
                    togglethis(thistarget, thischeckbox);
                });
                togglethis(thistarget, thischeckbox);
            });
        },
		/**
		 * ADMIN
		 * toggleTree: This function toggles the tree navigation in the tree view for the cms
		 */
        toggleTree: function(settings)
        {
            var s = $.extend({
                iconOpen: '/media/pics/cms/arrow-open.png',
                iconClose: '/media/pics/cms/arrow-close.png'
            }, settings);
            
			/** 
			 * control key for this function is shift
			 * added some event listeners for this function
			 * to use the shift click functionality
			 */
			var shift = false;
			
			$(document).keydown(function(e){
				if(e.keyCode == 16) {
					shift = true;
				}
			}).keyup(function(e){
				if(e.keyCode == 16) {
					shift = false;
				}
			});
			
            $(this).click(function(){
                var thisarrow = $(this);
                var id = thisarrow.attr('id').split('_')[1];
                var thistr = thisarrow.parents('tr').eq(0);
                var closeid = thistr.attr('class').split('_')[1];
                var closeTreeDepth = thistr.attr('rel');
                var trlist = thistr.nextAll();
                
				if(shift){
					// Open all levels 
	                thisarrow.attr('rel', '-').find('.treeIcon').attr('src', s.iconOpen).parents('td').eq(0).css('font-weight', 'bold');
	                
	                for (i = 0; trlist.eq(i).attr('rel') * 1 > closeTreeDepth * 1; i++) {
	                    trlist.eq(i).show();
	                    trlist.eq(i).find('.parent').attr('rel', '-').find('.treeIcon').attr('src', s.iconOpen).parents('td').eq(0).css('font-weight', 'bold');
	                }
				}
                else if (thisarrow.attr('rel') == '+') {
					// Open the next level down
                    thisarrow.attr('rel', '-').find('.treeIcon').attr('src', s.iconOpen).parents('td').eq(0).css('font-weight', 'bold');
					
                    $('.showHide_' + id).each(function(){
                        $(this).show();
                    });
                }
                else if (thisarrow.attr('rel') == '-') {
					// Close all levels
                    thisarrow.attr('rel', '+').find('.treeIcon').attr('src', s.iconClose).parents('td').eq(0).css('font-weight', 'normal');
                    
                    for (i = 0; trlist.eq(i).attr('rel') * 1 > closeTreeDepth * 1; i++) {
                        trlist.eq(i).hide();
                        trlist.eq(i).find('.parent').attr('rel', '+').find('.treeIcon').attr('src', s.iconClose).parents('td').eq(0).css('font-weight', 'normal');
                    }
                    
                }
                return false;
            });
        },
		/**
		 * ALL
		 * toggleValue: Set a default value for a text input that will dissappear 
		 * on the focus of that input
		 */
        toggleValue: function()
        {
            var thisField = $(this);
            var thisDefault = thisField.attr('defaultValue');
            thisField.focus(function(){
                if (thisField.val() == thisDefault) {
                    thisField.val('');
                }
            }).blur(function(){
                if (!thisField.val()) {
                    thisField.val(thisDefault);
                }
            }).parents('form').submit(function(){
                if (thisField.val() == thisDefault) {
                    thisField.val('');
                }
            });
        }
    });
})(jQuery);

