/*  -------------------------------------------------------------------
    Loader ------------------------------------------------------------- */
	(function($) {
		$.loader = function () {
	        return "<img src=\"/web/img/loader.gif\" alt=\"Loading...\" class=\"imgloader\" />";
        };
    })(jQuery);
	
	// Background Image Fix
	try { document.execCommand("BackgroundImageCache", false, true)} catch(e) {};


/* ------------------------------------------------------------------
    Load Function ---------------------------------------------------- */   
	(function($) {

		$.fn.loadFct = function () {
			
			//Only our html
			var $mainform = $("#mainform");
			var $main = $("#main", $mainform);
			var $sidebar = $("#sidebar", $mainform);
			
			//Add Corner to sidebar
			$sidebar
				.find(".block:first").addClass("first").prepend('<div class="tr"><\/div>')
				.end()
				.find(".block:last").addClass("last").append('<div class="bl"><\/div>')
				.end()
				.find(".ico").each(function(){
					var $link = $(this);
					$(this)
					.parents(".block:first")
					.bind("click", function(){
						location.href = $link.attr("href");
					})
					.addHover("overBlock");
					
					return this;
				 });
			
			//Bind Onchange Dropdown / Sidebar
			$("#select-new", $sidebar)
				.next().hide().end() //hide button
				.bind("change", function(){
					if($(this).val() !== "" && $(this).val() !== "/" ){
						location.href = $(this).val();
					}
				});
			
			
			//Fix ASP.Net form submit
			$mainform.SubmitListener();
						
			
			//Toolbox: Show utilities if javascript
			$("#toolbox ul", $sidebar)
				.removeClass("hide")
				.find(".b_size")
				.switchSize();
			
			
			//For Search Fields
			$("#frm-search .inp_search", $mainform)
				.bind("focus",function(){ if($.trim(this.value)==this.title){ this.value = ""; } })
				.bind("blur",function(){ if($.trim(this.value)==""){ this.value = this.title; } })
				.blur();
			
			
			//Custom Rating radio
			$(".rating_box", $main).find(":radio").rating(); 
			
			
			//FAQ
			$("#faq_listing", $main)
				.find(".b_go").css("visibility", "hidden") //Hide Select Btn, if javascript
				.end()
				.find("a:not(':last')") //Close all FAQ's item 
					.each(function(){ 
						//Open FAQ Item, if match hash
						if(!$(this).is('[name=' + location.hash.slice(1) +']')) {
							$(this).parent().addClass("close"); 
						}
					});
					
			//Toggle Registration Profile
			$("#toggle_personal", $main).each(function(){
				var $hiddenField = $(this).next();
				$(".b_arrow", this)
					.each(function(){
						$(this.hash).css("display", ($hiddenField.val() == 0) ? "none" : "");	
					})
					.bind("click", function(){ 
						$(this.hash).toggle(); 
						$hiddenField.val($hiddenField.val() == 0 ? "1" : "0")
						
						return false;
					}).show(); 
			}); 
			
			//Registration - Choose Your Bird
			$("#chooseyourbirds", $main).chooseYourBird();
			
			
			//Toggle field
			function selectMedication() {
				$(".selectMedication", $main)
					.each(function(){
						$(this).data("hidden_medication", $(".hidden_medication", $main).val());
						$("#li_DinNumber", $main).css("display", ($(this).val() == $(this).data("hidden_medication")) ? "" : "none");	
					})
					.bind("change.selectMedication", function(){
						$("#li_DinNumber", $main).css("display", ($(this).val() == $(this).data("hidden_medication")) ? "" : "none");
					});		
				return false;
			};
			
			$(".selectTouchYou", $main)
				.each(function(){
					$(this).data("hidden_touchyou", $(".hidden_touchyou", $main).val());
					if($(this).val() == $(this).data("hidden_touchyou")){
						$("#li_medication").show();
						selectMedication()
					}else{
						$("#li_medication").hide();
						$("#li_DinNumber").hide();
					}
				})
				.bind("change.selectTouchYou", function(){
					if($(this).val() == $(this).data("hidden_touchyou")){
						$("#li_medication", $main).show();
						
						//Toggle field	
						selectMedication()							
					}else{
						$("#li_medication", $main).hide();
						$("#li_DinNumber", $main).hide();
						$(".selectMedication", $main).unbind("change.selectMedication");
					}
				});
			
			
			//Ajax Loading Icons 
			$("#loading", $mainform)
				.prepend($.loader())
				.ajaxStart(function(){ $(this).show(); })
				.ajaxStop(function(){ $(this).hide(); });
						
			
			// Add rollover effect on img
			// Default: { classOver: ".ro", over: "_o" }
			$mainform.rollover();
			
			
			//External Links
			$mainform.externalLinks();
			
			
			//Fix Small Content
			$main
				.each(function(){
					var h = $(this).height();
					//Same Height as the sidebar
					if(h < $sidebar.height()){
						h = $sidebar.height();
						if($(this).hasClass("Left_Body_Right")){
							$(".col_right", this).css('min-height', h+'px');
						}else{
							$(this).css('min-height', h+'px');
						}
					}else{
						//Min-Height of 450px
						if(h < 450){
							if($(this).hasClass("Left_Body_Right")){
								$(".col_right", this).css('min-height', '450px');
							}else{
								$(this).css('min-height', '450px');	
							}
							
						}
					}
				});
			
			//Fix IE
			if($.browser.msie && $.browser.version < 8){
				
				//For Input Fields
				// Default: { classFocus: "inpFocus" }
				$mainform.inpFocus();
				
				//Fix IE6 Only
				if($.browser.version < 7){
					
					// Fix button:hover
					$(".btn", $mainform).addHover("overBtn");
					
					// PNG Transparency
					$("#interactivePH", $mainform).find(".mybird")
						.each(function(){
							var src = this.currentStyle.backgroundImage.split('"')[1]; 
							$(this).css('background-image', 'none');
							this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='image')";
						});  
					
					//Add an iframe to prevent select options from bleeding through
					jQuery('<iframe id="ieFrame" src="javascript:;">')
						.css({
							display: 'none',
							opacity: 0, 
							position: 'absolute', 
							height: jQuery('#main').height(), 
							width: '100%',
							zIndex: 1000, 
							top: 0, 
							left: 0 
						})
						.appendTo('#main');
					
					$main.fixAbbr();
				}
			};
			
			//for Forum User Profile
			
			findProfileLinkAndRemove();
			
			return this;
		};

	})(jQuery);


/* ------------------------------------------------------------------
    Reload Captcha -------------------------------------------------- */
	function reloadCaptcha() {
		//Find actual img
		var $img = jQuery(".img_captcha");
        	img = new Image();
			img.src = $img.attr("src");
			$img.attr("src", img.src + "&reload");
		
		//Clear the field
		$img.next().find(":input").clearFields();
		
		return false;
	};	


/* ------------------------------------------------------------------
    Popins ---------------------------------------------------------- */
	var current_popin = '';
	
	function openPopin(which, url){
		if( current_popin == which ){ closePopin(true); } // Popin is already open
		else{
			var $popin;
			
			if( current_popin != '' ) { closePopin(false); } 
			
			// Create Popin
			$popin = jQuery(createPopin(which));
						
			// Set current Popin
			current_popin = which;
			if(which == 'share'){
				$popin
					.find(".popin_content")
					.html(createShare())
					.bindEvents(which, url)
					.end()
					.prependTo("#main")
					.animatePopin(which,url);
			}else{
				//Format url for popin
				url = url.replace(/forms/, 'forms/popin');
				
				jQuery.ajax({
					type: "POST",
					url: url,
					data: {},
					success: function (resp) {
						//Insert Popin content
						$popin
							.find(".popin_content")
							.getContent(which, resp)
							.bindEvents(which, url)
							.fixCallback(resp)
							.end()
							.attr("class", "popin_"+which)
							.prependTo("#main")
							.animatePopin();
						
						//Fix IE6 Select
						jQuery("#ieFrame", "#main").show();
						//jQuery("select", "#main").css("visibility", "hidden");
					}
				});
			}
		}
    };
    
    function closePopin(hideIframe){
        //Find Popin and remove it
		jQuery("#popin", "#main")
			.animate({ width:0, opacity:0 }, 1200, function(){
				jQuery(this).remove();
				
				if(hideIframe){
					//Fix IE6 Select
					jQuery("#ieFrame", "#main").hide();
				}
			});

		// Clean up bind
		jQuery().unbind('.bindEvents');
		
		//Empty current Popin
		current_popin = "";
		
		return false;
    };
	
	function createPopin(type){
        var closeBtn = jQuery("#closeBtn").val();
		var html = '<div id="popin" class="popin_'+type+'">';
            if (type == "stf"){ 
            html += '    <span class="popin_feather"><\/span>'; 
            html += '   <input type="hidden" name="url" value="' + window.location.href + '" \/>';
            }
            html += '     <div class="popin_ctop"><a href="javascript:;" onclick="return closePopin(true);" class="b_close">'+ closeBtn +'<\/a></div>';
            html += '   <div class="popin_content clearfix"><\/div>';
            html += '   <input type="hidden" name="ajaxPost" value="yes" \/>';
            html += '   <div class="popin_cbot"><\/div>';
            html += '<\/div>';
        return html;
    };


 /* ------------------------------------------------------------------
    Share ------------------------------------------------------------ */   
	function createShare(){
        var url   = encodeURIComponent(document.location.href);
        var title = encodeURIComponent(document.title);
        var html  =  '<ul class="share-list">';
            html += '<li><a href="http://www.facebook.com/sharer.php?u='+url+'" class="b_facebook"><span>Facebook<\/span><\/a><\/li>';
            html += '<li><a href="http://del.icio.us/post?v=4&noui&amp;jump=close&amp;url='+url+'&amp;title='+title+'" class="b_delicious"><span>Delicious<\/span><\/a><\/li>';
            html += '<li><a href="http://digg.com/submit?phase=2&amp;url='+url+'&amp;title='+title+'" class="b_digg"><span>Digg<\/span><\/a></li>';
            html += '<li class="last"><a href="http://www.stumbleupon.com/submit?url='+url+'&amp;title='+title+'" class="b_stumbleupon"><span>StumbleUpon<\/span><\/a><\/li>';
            html += '<\/ul>';
         return html;
    };

	
/*  ------------------------------------------------------------------
    Fix Css Height + Sitecore Edit/Debug/Seo Mode -------------------- */
	function fixModeSitecore() {
		if (jQuery("body").children().not("form").size() > 1) {
			jQuery("#mainform").css({ "min-height": "100%", "height": "auto" });
		};
	};


/*  ------------------------------------------------------------------
    Forum Functions -------------------------------------------------- */
	function ToggleMenuOnOff (menuName) {
		jQuery("#"+menuName).toggle();
	};


// This will fix the links to a user
// It will remove any js or link to the user profile
    function findProfileLinkAndRemove()
    {
        jQuery("span,a").each(function(e, ui){
            links = isLinkProfileType(jQuery(this));
            if(links.profile)
            {
               if(links.type == "onclick")
               {
                    oncl = jQuery(this).attr("onclick").toString();
                    if(oncl.split('"')[1] != null)
                    {
                        getPath = oncl.split('"')[1].replace('"').replace(")").replace(";");
                        jQuery(this).attr("onclick", "");
                    }
               }
               
               if(links.type == "href")
               {
                   jQuery(this).replaceWith('<b><span class="inlineLink">' + jQuery(this).html() + '</span></b>');
               }
               
            }
        });
    }
    
    function isLinkProfileType(obj)
    {
        var ret = {};
        ret.type = getLinkType(obj);
        ret.profile = isLinkType(obj) ? hasProfileLink(obj.attr(getLinkType(obj)).toString()) : false;
        return ret;
    }
    
    function hasProfileLink(str)
    {
        return str.indexOf("Profile.aspx") >= 0 ? true : false;
    }
    
    function getLinkType(obj)
    {
        if(obj.attr("href") != null)
        {
            return "href";
        }
        
        if(obj.attr("onclick") != null)
        {
            return "onclick";
        }
        
        return "";
    }
    
    function isLinkType(obj)
    {
        if(obj.attr("onclick") != null)
        {
            return true;
        }
        
        if(obj.attr("href") != null)
        {
            return true;
        }
        
        return false;
    }

/*  ------------------------------------------------------------------
    Forum Functions -------------------------------------------------- */
	/*function ToggleSendToFriend() {
		sendToFriendForm = document.getElementById('SendToFriendForm');
		sendToFriendButton = document.getElementById('SendToFriendButton');
		if (sendToFriendForm.style.visibility == "hidden") {
			sendToFriendForm.style.visibility = "visible";
			sendToFriendForm.style.display = 'block';
		} else {
			sendToFriendForm.style.visibility = "hidden";
			sendToFriendForm.style.display = 'none';
		}
	
		sendToFriendForm.style.left = getposOffset(sendToFriendButton, "left") - (sendToFriendForm.offsetWidth / 2) + (sendToFriendButton.offsetWidth / 2);
		sendToFriendForm.style.top = getposOffset(sendToFriendButton, "top") + sendToFriendButton.offsetHeight;
	};
	
	function ToggleAddComment() {
		commentMenu = document.getElementById('CommentMenu');
		commentButton = document.getElementById('CommentButton');
		
		commentMenu.style.left = getposOffset(commentButton, "left");
		commentMenu.style.top = getposOffset(commentButton, "top") + commentButton.offsetHeight;
	
		if (commentMenu.style.visibility == "hidden") {
			commentMenu.style.visibility = "visible";
			commentMenu.style.display = 'block';
		} else {
			commentMenu.style.visibility = "hidden";
			commentMenu.style.display = 'none';
		}
	};
	
	function ToggleGalleryThumbnail(pictureID) {
		largeThumbDiv = document.getElementById('SecondaryThumbDiv' + pictureID);
		smallThumb = document.getElementById('SmallThumb' + pictureID);
		
		if (largeThumbDiv.className == "secondaryThumbnailHidden") {
			largeThumbDiv.className = "secondaryThumbnailPopup";
			largeThumbDiv.style.left = getposOffset(smallThumb, "left") - ((largeThumbDiv.offsetWidth - smallThumb.offsetWidth) / 2) + "px";
			largeThumbDiv.style.top = getposOffset(smallThumb, "top")  - ((largeThumbDiv.offsetHeight - smallThumb.offsetHeight) / 2) + "px";
			setTimeout(function() { largeThumbDiv.style.visibility = "visible"; }, 5);
		} else {
			largeThumbDiv.className = "secondaryThumbnailHidden";
		}
	};
	
	function ToggleRateMenu() {
		rateMenu = document.getElementById('RateMenu');
		rateButton = document.getElementById('RateButton');
		
		rateMenu.style.left = getposOffset(rateButton, "left");
		rateMenu.style.top = getposOffset(rateButton, "top") + rateButton.offsetHeight;
		
		if (rateMenu.style.visibility == "hidden") {
			rateMenu.style.visibility = "visible";
			rateMenu.style.display = 'block';
		} else {
			rateMenu.style.visibility = "hidden";
			rateMenu.style.display = 'none';
		}
	};
	
	function ToggleSearchMenu() {
		searchMenu = document.getElementById('SearchMenu');
		searchButton = document.getElementById('SearchButton');
		
		searchMenu.style.left = getposOffset(searchButton, "left");
		searchMenu.style.top = getposOffset(searchButton, "top") + searchButton.offsetHeight;
		
		if (searchMenu.style.visibility == "hidden") {
			searchMenu.style.visibility = "visible";
			searchMenu.style.display = 'block';
		} else {
			searchMenu.style.visibility = "hidden";
			searchMenu.style.display = 'none';
		}
	};
	
	function getposOffset(what, offsettype){
		var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
		var parentEl=what.offsetParent;
		while (parentEl!=null){
			totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
			parentEl=parentEl.offsetParent;
		}
		return totaloffset;
	};
	

	
	function OpenWindow (target) { 
		window.open(target, "_Child", "toolbar=no,scrollbars=yes,resizable=yes,width=400,height=400"); 
	}
	
	function OpenPostWindow (target) { 
		window.open(target, "_Child", "resizable=yes,width=500,height=700"); 
	}
*/

	
	
	
	
