// sidebar member slider plugin
(function($){
    $.fn.memberSlider = function(){
        return this.each(function(){
            var context = $(this),
                list = $(".member-list", context),
                staffMember = list.find(".member"),
                memberCount = staffMember.length,
                width = staffMember.width() + parseInt( staffMember.css("margin-right") ),
                index = 1,
                arrowLeft = $(".member-left", context),
                arrowRight = $(".member-right", context);
            
            function updateArrows() {
                if(index == 1) {
                    arrowLeft.css("visibility", "hidden");
                    arrowRight.css("visibility", "visible");
                } else if(index == memberCount) {
                    arrowLeft.css("visibility", "visible");
                    arrowRight.css("visibility", "hidden");
                } else {
                    arrowLeft.css("visibility", "visible");
                    arrowRight.css("visibility", "visible");
                }
            }
            
            arrowLeft.click(function(e){
                if(index > 1) {
                    var currentLeft = parseInt(list.css("left"));
                    list.animate({
                        left: (currentLeft + width) + "px"
                    });
                    index--;
                    updateArrows();
                }
                
                e.preventDefault();
            });
            
            arrowRight.click(function(e){
                if(index < memberCount) {
                    var currentLeft = parseInt(list.css("left"));
                    list.animate({
                        left: (currentLeft - width) + "px"
                    });
                    index++;
                    updateArrows();
                }
                
                e.preventDefault();
            });
            
        });
    };
    
    $.fn.profilePager = function(options){
		var self = $(this),
			items = self.find(options.itemSelector),
			prevBtn = self.find(options.prevButtonSelector),
			nextBtn = self.find(options.nextButtonSelector),
			textPrev = self.find(options.prevTextSelector),
			textNext = self.find(options.nextTextSelector),
			count = items.length,
			page = 1,
			itemsPerSet = options.setCount || 5;
		
		function updatePagedPane() {
			var start = (itemsPerSet * (page - 1));
				items
					.hide()
					.slice(start, start + itemsPerSet)
						.show();
			
			if(count <= itemsPerSet) {
				
			} else {
			
				if(page === 1) {
					textPrev.show();
					textNext.hide();
					prevBtn.hide();
					nextBtn.show();
				} else if((page * itemsPerSet) >= count) {
					textPrev.hide();
					textNext.show();
					prevBtn.show();
					nextBtn.hide();
				} else {
					textPrev.hide();
					textNext.hide();
					prevBtn.show();
					nextBtn.show();
				}
			
			}
		}
		
		prevBtn.click(function(e){
			e.preventDefault();
			page--;
			updatePagedPane();
		});
		
		nextBtn.click(function(e){
			e.preventDefault();
			page++;
			updatePagedPane();
		});
		
		updatePagedPane();
		
		return self;
	};
    
})(jQuery);

//function to equalize column lengths
jQuery.fn.equalHeights=function() {
    var maxHeight=0;
    this.each(function(){
     if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
    });
    this.each(function(){
     jQuery(this).height(maxHeight + "px");
     if (this.offsetHeight>maxHeight) {
         jQuery(this).height((maxHeight - (this.offsetHeight - maxHeight)) + "px");
     }
    });
};

function popitup(url) {
	newwindow=window.open(url,'name','height=400,width=550');
	if (window.focus) {newwindow.focus()}
	return false;
}

function displayThankYouButtons() {
	jQuery(".submit-again, .gallery").show();
}


// search box
function newSearch() {
    if (document.getElementById('q').value == 'Search') {
        document.getElementById('q').value = '';
        document.getElementById('q').style.fontWeight = 'normal';
    } 
}
function doSearch() {
    if (document.getElementById('q').value != 'Search' && document.getElementById('q').value != '') {
        document.location = '/search.asp?q=' + escape(document.getElementById('q').value);
    }
}


//alphanumeric only
function alphanum(testVal){
	 if ( !/^[0-9a-zA-Z\s]+$/i.test(testVal) ) 
		{
			return false;
		} 
	return true;
}


var videoInstr = "Choose a video (flv, avi or mov. Max 10MB)";
var imageInstr = "Choose an image (jpg, gif or png. Max 3MB)";

//swap functions for ratings
jQuery(document).ready(function() {
    jQuery('#q').keyup(function(e) {
        if(e.keyCode == 13) {
          doSearch();
        }
    })

	jQuery(".RateControlReadOnly").hover(
        function() {
        	jQuery(".ratingSumContainer").css('display', 'none');
        	jQuery(".loginToRate").css('display', 'inline');
        },
        function() {
        	jQuery(".ratingSumContainer").css('display', 'inline');
        	jQuery(".loginToRate").css('display', 'none');
        }
    );

	jQuery(".ratingOff").hover(
        function() {
        	jQuery(".ratingSumContainer").css('display', 'none');
        	jQuery(".loginToRate").css('display', 'inline');
        },
        function() {
        	jQuery(".ratingSumContainer").css('display', 'inline');
        	jQuery(".loginToRate").css('display', 'none');
        }
    );

	jQuery(".loginToRate").hover(
        function() {
        	jQuery(".loginToRate").css('display', 'inline');
        	jQuery(".ratingSumContainer").css('display', 'none');
        	
        },
        function() {
        	jQuery(".loginToRate").css('display', 'none');
        	jQuery(".ratingSumContainer").css('display', 'inline');
        }
    );

    // function to remove story number information from front end display
    jQuery(".removeStoryID").each(
		function(i) {
		    var titleArray = new Array();
		    titleArray = jQuery(this).text().split('#');
		    var newTitle = titleArray[0].replace(/\s+$/,""); 
			jQuery(this).text(newTitle);	
		}
	);
    
	// Remove port 170 from links
	jQuery("a").each(
		function(i) {
			if (jQuery(this).attr("href")) {
				var newValue = jQuery(this).attr("href").replace(":170/", "/");
				jQuery(this).attr("href", newValue);
			}
		}
	);

	// Fix broken image links : cfs-file.ashx >> cfs-filesystemfile.ashx
	jQuery("img").each(
		function(i) {
			if (jQuery(this).attr("src")) {
				var newValue = jQuery(this).attr("src").replace("cfs-file.ashx", "cfs-filesystemfile.ashx");
				jQuery(this).attr("src", newValue);
			}
		}
	);

	jQuery(".icon-blog-post:odd").addClass("right");

	jQuery(".comment-date").each(
		function() {
			jQuery(this).text(jQuery(this).text() + ":");
		}
	);

	jQuery(".CommonCommentContent-TheIcon-Body").each(
		function() {
			jQuery("div p:last", this).css("margin-bottom", "0");

			if (jQuery(this).height() < 74) {
				//jQuery(this).height(74);
			}

			jQuery(this).children().each(
				function() {
					if (this.className == "public-badge-info") {
						var height_this = jQuery(this).height();
						var height_parent = jQuery(this).parent().height();
						var marginTop = (height_parent - height_this) / 2;

						jQuery(this).css("margin-top", marginTop);
					}
				}
			);
		}
	);

//	jQuery(".fuHidden").filestyle({
//		image: "/community/themes/footjoy/images/icon/btn-browse.gif",
//		imageheight: 24,
//		imagewidth: 81,
//		width: 406
//	});
    jQuery(".fuHidden").attr("readonly",true);
    
	jQuery(".upload-video .file").val(videoInstr);
	jQuery(".upload-image .file").val(imageInstr);

	jQuery(".txtStoryTitle_WithVideo, .txtStoryTitle_NoVideo").focus(
		function() {
			if (jQuery(this).val() == "Enter story title") {
				jQuery(this).val("");
			}
		}
	);

	jQuery(".txtStoryTitle_WithVideo, .txtStoryTitle_NoVideo").blur(
		function() {
			if (jQuery(this).val() == "") {
				jQuery(this).val("Enter story title");
			}
		}
	);

	jQuery(".upload-video .file").blur(
		function() {
			if (jQuery(this).val() == "") {
				jQuery(this).val(videoInstr);
			}
		}
	);
	jQuery(".upload-image .file").blur(
		function() {
			if (jQuery(this).val() == "") {
				jQuery(this).val(imageInstr);
			}
		}
	);

	jQuery(".reset").click(
		function() {
			jQuery(".txtStoryTitle_WithVideo, .txtStoryTitle_NoVideo").val("Enter story title");
			jQuery(".upload-video .file").val(videoInstr);
			jQuery(".upload-image .file").val(imageInstr);
			jQuery(".txtStory > textarea").val("");
		}
	);

	jQuery(".submit-with-video").click(
		function() {
			var errors = false;
			var msg = "The following fields are required:";
			var title = jQuery(".txtStoryTitle_WithVideo").val();
			var video = jQuery(".upload-video .file").val();

			if (title == "" || title == "Enter story title") {
				errors = true;
				msg += "\n- Story Title";
			}
			// check for illegal chars
			if(!alphanum(title)) {
                errors = true;
				msg += "\n- Your Story Title Contains an Invalid Character";
            }
			if (video == "" || video == videoInstr) {
				errors = true;
				msg += "\n- Video";
			}
			else {
				var fileType = video.substring(video.indexOf(".") + 1);

				if (fileType != "flv" &&
					fileType != "mov" &&
					fileType != "avi") {

					if (errors) {
						msg += "\n\nThe file type of the video you chose to upload is not supported.  Please upload a video of type FLV, MOV or AVI.";
					}
					else {
						errors = true;
						msg += "The file type of the video you chose to upload is not supported.  Please upload a video of type FLV, MOV or AVI.";
					}
				}
			}

			if (errors) {
				alert(msg);
				return false;
			}
			else {
//				tb_show("Thank You", "/community/blogs/icon/sharestory.aspx#TB_inline?height=225&width=631&inlineId=hiddenModalContent", "");
//				jQuery("#thankyou").show();
//				setTimeout("displayThankYouButtons()", 5000);
			}
		}
	);

	jQuery(".submit-no-video input").click(
		function() {
			var errors = false;
			var msg = "";
			var image = jQuery(".upload-image .file").val();
			var title = jQuery(".txtStoryTitle_NoVideo").val();
			var body = jQuery(".txtStory > textarea").val();

			jQuery(".txtStory > textarea").addClass("txtStory");

			if (image == "" || image == imageInstr) {
			    // this case has been removed now that the image is optional
				//errors = true;
				//msg += "The following fields are required:";
				//msg += "\n- Image";
			}
			else {
				var fileType = image.substring(image.lastIndexOf(".") + 1).toLowerCase() ;

				if (fileType != "jpg" &&
					fileType != "jpeg" &&
					fileType != "gif" &&
					fileType != "png") {

					errors = true;
					msg = "The file type of the image you chose to upload is not supported.  Please upload an image of type JPG, JPEG, GIF or PNG.";
				}
			}
            // check for illegal chars
			if(!alphanum(title)) {
                errors = true;
				msg += "\n- Your Story Title Contains an Invalid Character";
            }
			if (title == "" || title == "Enter story title") {
				if (errors) {
					if (msg.indexOf("The following fields are required:") > -1) {
						msg += "\n- Story Title";
					}

					else {
						msg += "\n\nThe following fields are required:";
						msg += "\n- Story Title";
					}
				}
				else {
					errors = true;
					msg += "The following fields are required:";
					msg += "\n- Story Title";
				}

			}

			if (body == "") {
				if (errors) {
					if (msg.indexOf("The following fields are required:") > -1) {
						msg += "\n- Message";
					}
					else {
						msg += "\n\nThe following fields are required:";
						msg += "\n- Message";
					}
				}
				else {
					errors = true;
					msg += "The following fields are required:";
					msg += "\n- Message";
				}
			}

			if (errors) {
				alert(msg);
				return false;
			}
			else {
//				tb_show("Thank You", "/community/blogs/icon/sharestory.aspx#TB_inline?height=225&width=631&inlineId=hiddenModalContent", "");
//				jQuery("#thankyou").show();
//				setTimeout("displayThankYouButtons()", 5000);
			}
		}
	);

	jQuery(".thankyou-trigger").click(
		function() {
			jQuery("#thankyou").css("display", "block");
		}
	);

	jQuery(".the-icon-most-viewed-body ol li:last").addClass("last");
});


// User Profile: Review swapper

function ReviewSwapper() {

	var $ = jQuery,			// fix scoping issue 
		nToShow = 2, 		// number of reviews to show at once
		slideDelay = 1000,	// millisecond delay between slide up and slide down
		index = 0, 			// index of review to show; defaults the 0
		reviews = $("div[id$=_pnlReviews]").find("div.CommonContentBoxContent").find("ul.CommonContentBoxList"),
		numOfReviews = reviews.length,
		prev = $("a.prevRev"),
		next = $("a.nextRev"),
		isIE = $.browser.msie;

	review(); // init for the first time so pass no argument

	// swap the reviews to the review starting with the given index
	function review(item) {
		var isInit = false;
		if (item == null) {
			item = 0;
			isInit = true;
		}
		index = item;

		if ((index + nToShow) >= numOfReviews) {
			next.hide();
		} else {
			next.show();
		}

		if (index === 0) {
			prev.hide();
		} else {
			prev.show();
		}

		reviews.each(function(i) {
			if (i >= item && i <= (item + nToShow - 1)) {

			} else {
				if (isIE) {
					$(this).hide();
				} else {
					if (isInit) {
						$(this).hide();
					} else {
						$(this).hide("slow");
					}
				}
			}
		});

		//after a delay, slide the new reviews down
		setTimeout(function() {
			reviews.each(function(i) {
				if (i >= item && i <= (item + nToShow - 1)) {
					if (isIE) {
						$(this).show();
					} else {
						$(this).show("slow");
					}
				}
			});
		}, slideDelay);

	}

	prev.click(function() {
		review(index - nToShow);
		return false;
	});

	next.click(function() {
		review(index + nToShow);
		return false;
	});

}
