//include video 
MSLO_include_js('/images/assets/script/video.js', 'videoScriptId');


// text resize script
$j(document).ready(function() {
	$j("div.text-resize li a").click(function() {
		resizeText($j(this));
		return false;
	});
	
	$j(".addcomment a").click(function() {
		$j("#commentformcontainer").slideDown();
		$j(this).addClass("active");
		return false;
	});
	
	$j("#comments:not(.expandedview) input[type=reset]").click(function() {
		$j("#commentformcontainer").slideUp();
		$j(".addcomment a.active").removeClass("active");
	});

	$j("#comment-cancel-button").click(function() {
		$j("#commentformcontainer").slideUp();
		$j(".addcomment a.active").removeClass("active");
	});

	$j(".report").click(function() {
		report_comment_id = this.getAttribute("id");
		modalBox('report');
		return false;
	});
	
	$j(".delete").click(function() {
		delete_comment_id = this.getAttribute("id");
		modalBox('deleteComment');
		return false;
	});
	
	$j(".enlarge a").click(function() {
		
		// tb_show(caption, url, imageGroup)
		if ($j("#enlargeImage")) {
			$j("#enlargeImage").remove();
		}
		
		var u = generateEnlargedForm($j(this));
		if (u) {
			// console.log(u);
			tb_show('',u,'');
		}

		return false;
	});
	
	
	
	/* AKC Registered Trademark wankery */

	$j("h1").each(function(i) {
		var enc = encodeURIComponent($j(this).html());
		var reg_replace = '%C2%AE';
		if (enc.indexOf(reg_replace) != -1) {
			var start = encodeURIComponent("<sup>");
			var end = encodeURIComponent("</sup>");
			var hdr = enc.substr(0, enc.indexOf(reg_replace));
			hdr += start;
			hdr += reg_replace;
			hdr += end;
			hdr += enc.substr(enc.indexOf(reg_replace)+6);
			var dec = decodeURIComponent(hdr);
			$j(this).html(dec);
		}
	});
	
	
	/* Print Window functions */

	$j("#printwindow .buttons input").click(function() {
		if ($j(this).attr("src").indexOf("print") > -1) {
			window.print();
		}
		if ($j(this).attr("src").indexOf("cancel") > -1) {
			window.close();
		}
	});
	
	
	/* ugc share layout tweak */
	
	$j(".ugc_share li:even").css("clear","left");



	/* begin pets adoption js */
	
	//toggle switch to show and hide info
	
	
    $j(".toggle-switch").toggle(
    	function(){
    		$j(".toggled-content").show();
       		$j(".toggle-switch").addClass("toggle-on");
    	},
    	function(){
    		$j(".toggled-content").hide();
    		$j(".toggle-switch").removeClass("toggle-on");
    	}
    );
    
    if($j(".no-results").length != 0) {
    	$j(".toggle-switch").trigger("click");
    }

   	//tabs pet adoption main
    $j('.pet-img-cat').hide();
	$j('.tab-dog').addClass('active');
	
	
	$j('.tab-dog').click(function () {
		$j('.form-cat').hide();
		$j('.form-dog').show();
		$j('.tab-cat').removeClass('active');
		$j(this).addClass('active');
		var catVal = $j('.form-cat .city-zip').val();
		$j('.form-dog .city-zip').val(catVal);
		//alert(catVal);
		return false;
	})
	$j('.tab-cat').click(function () {
		$j('.form-dog').hide();
		$j('.form-cat').show();
		$j('.tab-dog').removeClass('active');
		$j(this).addClass('active');
		var dogVal = $j('.form-dog .city-zip').val();
		$j('.form-cat .city-zip').val(dogVal);
		//alert(dogVal);
		return false;
	})

	//validate zip, city, and state abbr on pet adoption form
	//$j(".validate-zip").empty();
	
	$j(".city-zip").focus(function(){
		$j(".validate-zip").empty();
		$j(".validate-zip").append('<span style="color:#666;">Enter a 5-digit zip code <br /> or a city (ex: Miami, FL).</span>');
		 $j(".city-zip").css('background-color', '#FBEEE8');
	});
	
	$j(".city-zip").blur(function(){
		$j(".validate-zip").empty();
	});
	
	$j(".adopt-form").submit(function () {
	
	
		//var theZip = $j(this).find(".city-zip").val();
		//$j(this).find(".city-zip").css('background-color','red');
		
	
        var valid_stuff = /(^\d{5}$)|[a-zA-Z]+, [a-zA-Z][a-zA-Z]$/;
  		//var zipContainerElement = $j($j(this).children().children()[0]);
        var char_length = $j(this).find(".city-zip").val().length;         
        if (char_length < 1) {
        	$j(".validate-zip").empty();
            $j(".validate-zip").append("Oops, you forgot to fill this in and it's required.");
            $j(this).find(".city-zip").css('background-color', '#FBEEE8');
            return false;
        } 
        else if (!$j(this).find(".city-zip").val().toString().match(valid_stuff)) {
        	$j(".validate-zip").empty();
            $j(".validate-zip").append("Please enter a valid zip code or city and state.");
            $j(this).find(".city-zip").css('background-color', '#FBEEE8');
            return false;
        }
        else {
        	$j(".validate-zip").empty();
        	//$j(".validate-zip").append('<span style="color:#069">Looks good to me!</span>');
        	return true;
        }

    });
    
    
    //show the 'back to search' link on pet adoption detail page only if coming from a search
    var from_search = document.referrer;
 	if ($j("body").hasClass("pet-adoption-detail") && !from_search.match(/(species)/)) {
		//alert(document.referrer);
		$j(".pet-detail a.seeall").hide();
	}
    
    
    //browse through the pet images in the pet adoption detail page 
    var img_total = $j(".pet-nav .img-total").html();
    var cur_img = 1;
    
    if (img_total != "1") {
    $j(".pet-nav a.next").click(function() {
    	if (img_total > cur_img) {
    	$j(".active-img").next("img").addClass("active-img");
		$j(".active-img").prev("img").removeClass("active-img");
		cur_img++;
		$j(".pet-nav .img-current").html(cur_img);
		}
	});
	
	$j(".pet-nav a.prev").click(function() {
    	if (img_total >= cur_img && cur_img > 1) {
    	$j(".active-img").prev("img").addClass("active-img");
		$j(".active-img").next("img").removeClass("active-img");
		cur_img--;
		$j(".pet-nav .img-current").html(cur_img);
		}
	});
	} else {
		$j(".pet-gallery .pet-nav").css("visibility", "hidden");
	}
	
	
	//swap the pet-adoption forms on select change
	$j(".form-dog #species").change(function(){
		$j(".form-dog select#species option[value='dog']").attr("selected","selected");
		$j(".form-dog select#species option[value='cat']").removeAttr("selected");
		$j(".form-dog").hide();
		$j(".form-cat").show();
		var dogVal = $j('.form-dog .city-zip').val();
		$j('.form-cat .city-zip').val(dogVal);
    });
    
    $j(".form-cat #species").change(function(){
    	$j(".form-cat select#species option[value='cat']").attr("selected","selected");
    	$j(".form-cat select#species option[value='dog']").removeAttr("selected");
    	var catVal = $j('.form-cat .city-zip').val();
		$j('.form-dog .city-zip').val(catVal);
		$j(".form-cat").hide();
		$j(".form-dog").show();
    });
    
    
    //show partner info when about is clicked in pet adoption main
    $j(".channel_dl .trans-bg").hide();
    
    $j(".partner-info a.close-box").click(function(){
    	$j(".channel_dl .trans-bg").fadeOut();
    	$j(".channel_dl .partner-info").fadeOut();
    });
    
    $j(".pet-search .about-partner").click(function(){
    	$j(".channel_dl .trans-bg").css('filter','alpha(opacity=80)').fadeIn();
       	$j(".channel_dl .partner-info").fadeIn();
 	});
	
	/* end pets adoption js */
	
});

function textareaMax(el, max, remain){

	// console.log("val: "+$j(el).val());
	
	var char_remain = (max - $j(el).val().length);
	if (char_remain <= 0) char_remain = 0;

	var str_char_remain = char_remain.toString();
	$j(remain).html(str_char_remain);
	
	if ($j(el).val().length > max) {
		$j(el).val($j(el).val().substring(0, max));
	}
	
}


function addPrintHandler(width, height) {
	$j("#printsubmit").click(function() {

			width = width*1 + 40;
			height = height*1 + 100;

			var newWin = window.open("","myNewWin","width="+width+",height="+height+",toolbar=0"); 			
			var a = window.setTimeout("document.getElementById('print_form').submit()", 500);
			return false;
		
	});
}


function generateEnlargedForm(el) {

	var container = $j(el).parents(".article_photo")[0] || $j(el).parents(".lead_photo")[0];
	
	var img = $j(container).children("img").attr("src");
	var size = $j(container).find(".enlarge a").attr("class").split(" ");
		for (var i = 0; i < size.length; i++) {
			if ((size[i] == "hd") || (size[i] == "xl")) {
				size = size[i];
				break;
			}
		}

	var caption = $j(container).find(".caption").html();
	var credit = $j(container).find(".credit").html();

	var displayImage = img.substring(0, img.lastIndexOf("_")+1)+size+".jpg";

	var width, height = new Number();
	var margin = 30;
	width = size == "xl" ? 370+(2*margin) : 500+(2*margin);
	height = size == "xl" ? 550+margin : 700+margin;

	var returnURL = "#TB_inline?height="+height+"&width="+width+"&inlineId=enlargeImage&modal=true";
	var formaction = "/portalext/inline/mslo_printimage.jsp";
	
	
	var enlargeForm = '<form action="'+formaction+'" method="POST" id="print_form" target=myNewWin>';
		enlargeForm += '<input type="hidden" name="caption" value="'+caption+'" />';
		enlargeForm += '<input type="hidden" name="credit" value="'+credit+'" />';
		enlargeForm += '<input type="hidden" name="image" value="'+displayImage+'" />';
		enlargeForm += '<input type="hidden" name="size" value="'+size+'" />';
		enlargeForm += '<input type="image" name="Print" value="Print" id="printsubmit" alt="Print this photo" src="http://images.marthastewart.com/images/assets/channel/pets/btn_printThisPhoto.gif"/>';
		enlargeForm += '</form>';
		
	var enlargeDiv = '<div id="enlargeImage">';
		enlargeDiv += '<div id="enlargeImageContainer">';
		enlargeDiv += '<a href="#close" id="enlargeClose">close</a>';
		enlargeDiv += '<img src="'+displayImage+'" />';
		enlargeDiv += '<div class="caption">'+caption+'</div>';
		enlargeDiv += '<div class="credit">'+credit+'</div>';
		enlargeDiv += enlargeForm;
		enlargeDiv += '</div>';
		enlargeDiv += '</div>';

	if ($j(container).append(enlargeDiv)) {
		$j("#enlargeClose").click(function() {
			tb_remove();
			return false;
		});

		addPrintHandler(width, height);
		return returnURL;
	}
	
	
	return false;	
}


function resizeText(e) {
	var size = $j(e).parent("li").attr("class");

	var m = "text-resize_medium";
	var l = "text-resize_large";
	
	var el = ".col1";

	$j(el).removeClass(m);
	$j(el).removeClass(l);

	if (size == "medium") {
		$j(el).addClass(m);
	}
	if (size == "large") {
		$j(el).addClass(l);
	}
}






engagement_toolbar = {

	//stores the current action that is trying to be performed
	currentaction : '',
	
	//stores user's logged-in status
	loginstatus : false,
	
	//setuponclicks
	setup_onclicks: function() {
		
		//comments pageup
		$j("textarea#comment").unbind().bind("keyup", function() {
			return textareaMax($j(this), $j(this).attr("maxlength"), "#comments-txt-count");
		});
		
		//save tag note pageup
		if (!document.getElementById("tag_limit")) {
			$j("#noteandtag h3 label").eq(0).after('<div id="tag_limit">(1000 characters maximum; <span id="tagcount">1000</span> remaining)</div>');
		}
		$j("#tags").bind("keyup", function() {
			return textareaMax($j(this), $j(this).attr("maxlength"), "#noteandtag h3 span#tagcount");
		});
		//save tag note pageup
		if (!document.getElementById("note_limit")) {
			$j("#noteandtag h3 label").eq(1).after('<div id="note_limit">(300 characters maximum; <span id="notecount">300</span> remaining)</div>');
		}
		$j("#note").bind("keyup", function() {
			return textareaMax($j(this), $j(this).attr("maxlength"), "#noteandtag h3 span#notecount");
		});
		$j("#note").bind("click", function() {
			if ($j(this).val() == 'Leave yourself a reminder, a tweak, an idea, or anything else related to this item.') {
				$j(this).val('');
			}
		});
		
		$j("#tags").bind("click", function() {
			if ($j(this).val() == 'Separate each tag with a comma. If this is a brownie recipe, you might type: chocolate, dessert, Sue\'s party') {
				$j(this).val('');
			}
		});
		


		
		//set up the onclick for the toolbar
		$j(".engagement .toolbar a").unbind().click(function() {
			var clickedid = $j(this).parent().attr('id');
			if (clickedid == 'engagement-print' || clickedid == 'engagement-email') {
				engagement_toolbar.currentaction = '';
				engagement_toolbar.close_all_drawers();
				return true;
			}
			engagement_toolbar.perform_action(this);
			return false;
		
		});
		// add drawer close button handler
		$j("a.engagement-close").unbind().click(function() {
			engagement_toolbar.currentaction = '';
			engagement_toolbar.close_all_drawers();
			return false;
		});
		// add share handlers
		$j("#share a").not(".engagement-close").click(function() {
			var svc = $j(this).attr("class");
			shareLink(svc);
			var passedaction = 'share_'+$j(this).attr('class');
			doTrackAction(passedaction);
			return false;
		});
		// activate Add Comment buttons
		$j(".addcomment a").click(function() {
			$j("#commentformcontainer").slideDown();
			$j(this).addClass("active");
			return false;
		});
		$j("#comment-cancel-button").click(function() {
			$j("#commentformcontainer").slideUp();
			$j(".addcomment a.active").removeClass("active");
		});
		// activate report and delete comment buttons
		$j(".report a").click(function() {
			report_comment_id = this.getAttribute("id");
			modalBox('report');
			return false;
		});
		$j(".delete a").click(function() {
			delete_comment_id = this.getAttribute("id");
			modalBox('deleteComment');
			return false;
		});
	},
	
	//closes the drawers and removes the highlight state
	close_all_drawers : function() {
		this.remove_highlights();
		$j('.engagement_drawer').slideUp(150);
		// return false;
	},
	
	//opens a drawer
	open_drawer : function(el) {
		// open the new drawer
		$j(el).addClass("highlight");
		$j(el).parent("li").addClass("engagement_open");
		$j(this.currentaction).slideDown(150);
		// return false;
	},
	//removes highlights& open status from all elements
	remove_highlights : function() {
		$j(".engagement a.highlight").removeClass("highlight");
		$j(".engagement li").removeClass("engagement_open");
		// return false;
	},
	setup_state: function(alreadysaved, alreadyrecommended, loginstatus) {
		this.loginstatus = loginstatus;
		if (alreadysaved) { engagement_toolbar.savetag.set_saved(); }
		if (alreadyrecommended) { engagement_toolbar.recommend.set_already_recommended(); }
		// return false;
	},
	update_state: function(alreadysaved, alreadyrecommended, recommendedCount) {
		if (alreadysaved) { engagement_toolbar.savetag.set_saved(); }
		engagement_toolbar.recommend.set_recommended_state(alreadyrecommended, recommendedCount);
		// return false;
	},
	update_comment_count: function(commentCount) {
		$j("#engagement-comment a").html("Comment (" + commentCount + ")");
		// return false;
	},
	//general method to perform an action in the toolbar 
	//(what is first called onclick)		
	perform_action: function(el) {
		//get the element that was clicked on
		tgt = $j(el).attr("href");
		
		if (tgt.indexOf("#") != 0) {
			tgt = tgt.substring(tgt.indexOf("#"));
		}
		
		
//		if ((tgt == '#recommend' || tgt == '#comment' || tgt == '#save') && this.loginstatus == false) {
//			alert('You must log in');
//			return false;
//		}
		//close all the drawers
		this.close_all_drawers();
		if (tgt == this.currentaction) { 
			//they clicked the bar again to close the box
			this.currentaction = '';
			return true;
		}
		else {
			//we setup the current action
			this.currentaction = tgt;
			$j(el).parent("li").addClass("engagement_open");
		}
		//switch depending on what we are trying to do
		switch(tgt) {
			case '#recommend':
				//if it is not set to inactive
				if (!$j(el).hasClass("inactive")) {
					//make it unclickable
					$j('#engagement-recommend a').unbind();
					oneClickRecommend();
					//switches to "Thanks!" (or passed arg) and adds the highlight
					this.currentaction = '';              
				}		
				break;
			case '#comments':
				this.remove_highlights();
				$j("#commentformcontainer").slideDown();
				window.location.hash = tgt;
				this.currentaction = '';
				break;
			case '#share':
				this.open_drawer($j(el));
				break;
			case '#facebook':
				this.open_drawer($j(el));
				break;
			case '#save':
				if ($j(el).hasClass("inactive")) {
					this.open_drawer(el);
				} else {
					save();
				}
				break;
		}
	},
	
	//functions for manipulating savestate
	savetag : {
		add_saving_highlight: function() {
			$j('#engagement-save a').addClass("highlight");
		},
		set_saved: function() {
			newtxt = $j('#engagement-save a').html().replace("Save", "Saved");
			$j('#engagement-save a').html(newtxt);
			$j('#engagement-save a').removeClass("highlight");
			$j('#engagement-save a').addClass("inactive");
			$j('#engagement-save span').show();
			// update text, bind tag & note drawer function to tag & note link
		}
	},
	
	//functions for manipulation the recommend state
	recommend : {
		//var for storing the text inside the element if it isnt manually reset
		currenthtml : '',
		
		//adds the highlight
		//stores the current html text - replacing recommend with recommended
		//then sets the html to either the processed text, or the txt passed as an arg
		switch_text : function(newtxt) {
			thxtext = (typeof(newtxt) == 'undefined') ? 'Thanks!' : newtxt;
			//get the current html so we can replace the copy yet maintain the # of recommendations
			this.currenthtml = $j('#engagement-recommend a').html();
			this.currenthtml = this.currenthtml.replace("Recommend", "Recommended");
			$j('#engagement-recommend a').addClass("highlight");
			$j('#engagement-recommend a').html(thxtext);
		},
		
		fade_close : function(newtxt) {
			resethtml = (typeof(newtxt) == 'undefined') ? this.currenthtml : newtxt;
			//fades current element then pops back up with new text
			$j('#engagement-recommend a').fadeTo(2000, 0.1, function() {
				//sets the html to either the stored var or the passed in txt
				$j('#engagement-recommend a').html(resethtml);
				//remove highlight
				$j('#engagement-recommend a').removeClass("highlight");
				//disables
				$j('#engagement-recommend a').addClass("inactive");
				//fades to off off state
				$j('#engagement-recommend a').fadeTo(2000, 1, function() {
					engagement_toolbar.close_all_drawers();
				});
			});
		},
		set_already_recommended: function() {
			newhtml = $j('#engagement-recommend a').html().replace("Recommend", "Recommended");
			$j('#engagement-recommend').html('<span href="#recommend" class="inactive"></span>');
			$j('#engagement-recommend span').html(newhtml);
			// return false;
		},
		set_recommended_state: function(isRecommended, recommendedCount) {
			if (isRecommended=="true") {
				$j('#engagement-recommend a').html( "Recommended (" + recommendedCount + ")");
				$j('#engagement-recommend a').addClass("inactive");
			} else {
				$j('#engagement-recommend a').html( "Recommend (" + recommendedCount + ")");
			}
 			// return false;
		}
	}
}


function marks_recommend_function() {
	//we are on a pets page, lets use the new toolbar
	//if you split up these method calls, you will want to wrap each in this if statement
	//otherwise they may fire on pages that dont have the new toolbar...
	if ($j('#pets')) {
		//switches to "Thanks!" (or passed arg) and adds the highlight
		engagement_toolbar.recommend.switch_text();
		//switches to disabled and updates text to recommended w/ the 
		//same # of recommendations (or passed arg)
		engagement_toolbar.recommend.fade_close();
	}
	else {
		//DOM manipulation that currently exists in the functions 
		//should be wrapped in the else (we dont want them to fire on the pets pages
	}
}

function marks_save_function() {
	if ($j('#pets')) {
		//set to active "Save" state
		engagement_toolbar.savetag.add_saving_highlight();
		//Switches to "Saved"
		engagement_toolbar.savetag.set_saved();
	}
}

function marks_onload_function() {
	if ($j('#pets')) {
		//setup the vars
		alreadysaved = false;
		alreadyrecommended = false;
		loginstatus = true;
	
		//setup the obj
		// engagement_toolbar.setup_onclicks();
		// engagement_toolbar.setup_state(alreadysaved, alreadyrecommended, loginstatus);
	}
}

$j(document).ready(function() {
	engagement_toolbar.setup_onclicks();
	//marks_onload_function()
});




function MSLO_include_js(path, id) {
// Create the Script Object
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = path;
	script.defer = true;
	script.id = id; 
	// Insert into head
	var head = document.getElementsByTagName('head').item(0);
	head.appendChild(script);
}





