YAHOO.util.Event.onDOMReady(function() {
    
    /**
    * The standard Bugsy JavaScript file.  When using must include the following components:
    * yahoo-dom-event, animations, json
    */
    YAHOO.namespace("bugsy");

    /**
    * Standard utility functions
    */
    YAHOO.bugsy.util = function() {
        return {
            /**
    		 * Used to strip html tags from a given string
    		 * @param {Object} str
    		 */
    		stripTags : function (strToClean) {
    			if (YAHOO.lang.isString(strToClean)) {
    				return strToClean.replace(/<\/?[a-z0-9]+>/gim, '');	
    			}
    		},
    		/**
    		 * Used to create a new DOM element
    		 * @param {Object} elem - Type if element to create (ex) div
    		 */
    		create : function (elem) {
    			return document.createElementNS ?
    					document.createElementNS('http://www.w3.org/1999/xhtml', elem) :
    					document.createElement(elem);
    		},
    		/**
    		 * Used to remove an element from the DOM
    		 * @param {Object} elem
    		 */
    		remove : function (elem) {
    		    if (YAHOO.lang.isObject(elem) && !YAHOO.lang.isUndefined(elem)) {
    		        try {
        				elem.parentNode.removeChild(elem);	
        			} catch (e) {}
    		    }
    		},
            /**
             * Used to count the number of elements in a JSON dataset since there is not length property
             * @param {Object} The object to count
             */
            countElementsinObject : function (obj) {
                var prop,
                    propCount = 0;

                for (prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                       propCount++;
                    }
                }

                return propCount;
            },
            /**
            * Used to constrain an input field to a set size
            * @param {Object} inputToLimit - id of input field to constrain
            * @param {Object} limit - max amount to allow
            */
            limitTextInput : function (inputToLimit, limit) {
                var inputNodeToLimit = YAHOO.util.Dom.get(inputToLimit),
                    crtVal           = YAHOO.util.Dom.get(inputToLimit).value;
                    
                if (crtVal.length > limit) {
                    inputNodeToLimit.value = inputNodeToLimit.value.substring(0, limit);
                }
            },
            /**
            * Handle ylogin and redirect to current page
            */
            doYloginAndReturn : function () {
                window.location = "http://login.yahoo.com/config/login_verify2?.done=" + encodeURIComponent(location.href);
                return;
            },
            /**
            * Basic error handling helper function used in place of multiple if statements
            */
            assert : function(condition, message) {
                if (condition === false) {
                    throw new Error(message);
                }
            }
        };
    }();

    YAHOO.bugsy.video = function() {
        return {
            setupYepVideo : function(yepId, vId, vThumbUrl) {
            	/**
            	 * Used to swap video players.  Sets up the YEP player.  Standard emed below for reference.
            	 * @param {Object} id
            	 * @param {Object} vid
            	 * @param {Object} vThumbUrl
            	 */
            	if (swfobject.hasFlashPlayerVersion("8.0.0")) {
                    var fn = function() {
                        var att = { data:"http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.30", width:"512", height:"322" };
                        var par = { 
                                    flashvars:"id=" + yepId + "&vid=" + vId + "&lang=en-us&intl=us&thumbUrl=" + vThumbUrl + "&embed=1",
                                    allowFullScreen: "true",
    					            allowScriptAccess: "always",
    					            wmode: "transparent"
                                  };
                        var id = "yep_container";
                        var myObject = swfobject.createSWF(att, par, id);
                    };
                    swfobject.addDomLoadEvent(fn);

            		//This player is larger than the live player so we need to remove some additional styling
            		YAHOO.util.Dom.removeClass('yep_container', 'live-player');
            	}
            },
            setupFOPVideo : function(vid, autostart) {
            	/**
            	 * Used to swap video players.  Sets up the YEP player.  Standard emed below for reference.
            	 * @param {Object} id
            	 * @param {Object} vid
            	 * @param {Object} vThumbUrl
            	 */

            	if (typeof autostart === 'undefined') {
            	    autostart = 0;
            	} 
        	
            	if (swfobject.hasFlashPlayerVersion("8.0.0")) {
                	var fn = function() {
    					var att = { data:"http://d.yimg.com/cosmos.bcst.yahoo.com/up/fop/embedflv/swf/fop.swf", width:"326", height:"281" };
    					var par = { 
    					            flashvars:"shareEnable=1&enableFullScreen=1&autoStart=" + autostart + "&id=" + vid,
    					            allowFullScreen: "true",
    					            allowScriptAccess: "always"
    					          };
    					var id = "yep_container";
    					swfobject.createSWF(att, par, id);
    				};
    				swfobject.addDomLoadEvent(fn);
            				
            		//This player is larger than the live player so we need to remove some additional styling
            		YAHOO.util.Dom.removeClass('yep_container', 'live-player');
            	}
            }
        };
    }();

    YAHOO.bugsy.effects = function() {
        return { 
            /**
    		 * Used to fade DOM elements
    		 * @param {Object (or dom id)} elementToFade
    		 * @param direction - Which way to fade?  In or out...
     		 * @param duration - How long should the effect last (default is 1 sec)
     		 * @param onStartCallback - A function to call before starting the animation
     		 * @param onCompleteCallback - A function to call after completing the animation
    		 * @param removeItToo - Optionally removes element from DOM after hiding (so only valid for fade out)
    		 */
    		fadeElement : function (elementToFade, direction, duration, onStartCallback, onCompleteCallback, removeItToo) {
    		    var fadeAnim,
    		        animAttributes,
    		        animElement = elementToFade;
    		    
    		    //Make sure we have a DOM node to process  
    		    if (!YAHOO.lang.isObject(animElement)) {
    		        animElement = YAHOO.util.Dom.get(animElement);
    		        
    		        YAHOO.bugsy.util.assert(!YAHOO.lang.isNull(animElement) && !YAHOO.lang.isUndefined(animElement), "function fadeElement: Unable to identify element to fade!");
    		    }
    		    
    		    YAHOO.bugsy.util.assert(direction === 'out' || direction === 'in', "function fadeElement: A valid direction must be given to perfom the fade animation!");
    		    if (direction === 'out') {
		            animAttributes = { opacity: { from: 1, to: 0 } };
		        } else if (direction === 'in') {
		            animAttributes = { opacity: { from: 0, to: 1 } };
		        }
    		    
    			fadeAnim = new YAHOO.util.Anim(elementToFade, animAttributes, duration, YAHOO.util.Easing.easeOut);
    			
    			//Is there an onStart event?
    			if (YAHOO.lang.isFunction(onStartCallback)) {
    			    fadeAnim.onStart.subscribe(onStartCallback);
    			}
    			
    			//Once the fade out is finished we hide the element completely
    			fadeAnim.onComplete.subscribe(function () {
    				if (!YAHOO.lang.isNull(removeItToo) && removeItToo !== false) {
    					YAHOO.bugsy.util.remove(animElement);
    				}
    				
    				//Are there additional onComplete events?
        			if (YAHOO.lang.isFunction(onCompleteCallback)) {
        			    onCompleteCallback();
        			}
    			});
		
    		    fadeAnim.animate();
    		    return animElement;
    		},
    		/**
    		 * Used as a status indicator (ex) highlight background yellow and fade back to original
    		 * @param {Object (or dom id)} elementToHighlight
     		 * @param startColor - what hex color code to start with
     		 * @param endColor - what hex color code to end with (probably the original)
     		 * @param duration - How long should the effect last (default is 1 sec)
     		 * @param onStartCallback - A function to call before starting the animation
     		 * @param onCompleteCallback - A function to call after completing the animation
    		 */
    		highlightElement : function (elementToHighlight, startColor, endColor, duration, onStartCallback, onCompleteCallback) {
    		    var highlightAnim,
    		        animDuration,
    		        animAttributes,
    		        animElement = elementToHighlight;
    		    
    		    //Make sure we have a DOM node to process  
    		    if (!YAHOO.lang.isObject(animElement)) {
    		        animElement = YAHOO.util.Dom.get(animElement);
    		        
    		        YAHOO.bugsy.util.assert(!YAHOO.lang.isNull(animElement) && !YAHOO.lang.isUndefined(animElement), "function highlightElement: Unable to identify element to highlight!");
    		    }
    		    
    		    YAHOO.bugsy.util.assert(YAHOO.lang.isString(startColor) && YAHOO.lang.isString(endColor), "function highlightElement: Start and end colors are required for element highlighting!");
    		    YAHOO.bugsy.util.assert(startColor[0] === '#' && endColor[0] === '#', "function highlightElement: Start and end color must be given in hex!");
    		    
    			animAttributes = {
    				backgroundColor: { from: startColor, to: endColor }
    			};
    			
    			animDuration = YAHOO.lang.isNumber(duration) ? duration : 0; //Duration of animation
		
    			highlightAnim = new YAHOO.util.ColorAnim(animElement, animAttributes, animDuration);
    			
    			//Is there an onStart event?
    			if (YAHOO.lang.isFunction(onStartCallback)) {
    			    highlightAnim.onStart.subscribe(onStartCallback);
    			}

    			//Is there an onComplete event?
    			if (YAHOO.lang.isFunction(onCompleteCallback)) {
    			    highlightAnim.onComplete.subscribe(onCompleteCallback);
    			}	
        			
    			highlightAnim.animate();
    			return animElement;
    		},
    		/**
    		 * Standard blind effects
    		 * @param {Object (or dom id)} elementToBlind
    		 * @param direction - Which way to blin?  Up or down
    		 * @param desiredHeight - Defaults to 0 which is ok for "down", but for "up" we need an endpoint
    		 * @param duration - How long should the effect last (default is 1 sec)
    		 * @param onStartCallback - A function to call before starting the animation
    		 * @param onCompleteCallback - A function to call after completing the animation
    		 */
    		blindElement : function (elementToBlind, direction, desiredHeight, duration, onStartCallback, onCompleteCallback) {
    		    var blindAnim,
    		        animDirection,
    		        animHeight,
    		        animDuration,
    		        animAttributes,
    		        animElement = elementToBlind;
    		    
    		    //Make sure we have a DOM node to process  
    		    if (!YAHOO.lang.isObject(animElement)) {
    		        animElement = YAHOO.util.Dom.get(animElement);
    		        
    		        YAHOO.bugsy.util.assert(!YAHOO.lang.isNull(animElement) && !YAHOO.lang.isUndefined(animElement), "function blind: Unable to identify element to blind!");
    		    }
    		    
    		    //Verify we have a valid direction
    		    YAHOO.bugsy.util.assert(direction === 'up' || direction === 'down', "function blind: A valid direction must be given to perfom the blind animation!");
    		    animDirection = direction;
    		    
    		    animHeight = YAHOO.lang.isNumber(desiredHeight) ? desiredHeight : 0; //Desired height of Element after animation
    		    animDuration = YAHOO.lang.isNumber(duration) ? duration : 0; //Duration of animation
    		    
    			animAttributes = {
    				height: { to: animHeight }
    			};
		
    			blindAnim = new YAHOO.util.Anim(animElement, animAttributes, animDuration);
    			
    			//Is there an onStart event?
    			if (YAHOO.lang.isFunction(onStartCallback)) {
    			    blindAnim.onStart.subscribe(onStartCallback);
    			}
    			
    			//Is there an onComplete event?
    			if (YAHOO.lang.isFunction(onCompleteCallback)) {
    			    blindAnim.onComplete.subscribe(onCompleteCallback);
    			}
    			
    			blindAnim.animate();
    			return animElement;
    		}
        };
    }();

    /**
    * Sets up the standard share widget.
    * 1) Include the share-widget.css file
    * 2) Add the button(s) as need with:
    * <a title="Title for share" href="http://intheknow.yahoo.com/blah/index.php?id=blah">
    *   <img class="share-widget" src="<?PHP CDN(); ?>images/share-widget/share_button.png" alt="share this" />
    * </a>
    * 3) Add the widget HTML just before the closing body:
    * <?PHP include "inc/widgets/share/share_widget.php"; ?>
    */
    YAHOO.bugsy.setupShareWidget = function() {
        //This setup function automatically sets up everything if there are any share widgets in the DOM
        if (!YAHOO.lang.isNull(YAHOO.util.Dom.get("share-widget-container"))) {
            var sendWidgetContainer  = YAHOO.util.Dom.get("send-widget-container"),
                shareWidgetContainer = YAHOO.util.Dom.get("share-widget-container"),
                activeStoryTitleNode = YAHOO.util.Dom.get("active_share_story_title"),
                activeStoryURLNode   = YAHOO.util.Dom.get("active_share_story_url");

            //We want to keep the share widgets portable and allow their events to work even if they are pull and re-entered into the DOM
            YAHOO.util.Event.on(document, 'click', function(e) {
                var x, y, eltarget = YAHOO.util.Event.getTarget(e);

                if (YAHOO.util.Dom.hasClass(eltarget, "share-widget")) {
                    YAHOO.util.Event.preventDefault(e);

                    //Activate share and make sure send is closed so there is no overlap
                    YAHOO.util.Dom.removeClass(shareWidgetContainer, "share-off");
                    if (!YAHOO.lang.isNull(sendWidgetContainer)) {
                        YAHOO.util.Dom.addClass(sendWidgetContainer, "share-off");
                    }
                    
                    x = YAHOO.util.Dom.getX(eltarget);
                    y = YAHOO.util.Event.getPageY(e) + 15; //getPageY used to work around a Safari issue
                    activeStoryTitleNode.value = YAHOO.util.Dom.getAttribute(eltarget.parentNode, "title");
                    activeStoryURLNode.value   = YAHOO.util.Dom.getAttribute(eltarget.parentNode, "href");

        		    YAHOO.util.Dom.removeClass(shareWidgetContainer, "share-off");
        		    YAHOO.util.Dom.setXY(shareWidgetContainer, [x, y]);
                }
            });
            
            YAHOO.util.Event.on("share-widget-close", 'mouseover', function(e) {
                this.style.cursor = 'pointer';
            });

            YAHOO.util.Event.on('share-widget-close', 'click', function(e) {
                YAHOO.bugsy.closeShareWidget();
            });

            //When a share network is selected we need to craft the proper share url
            YAHOO.util.Event.on(shareWidgetContainer, 'click', function(e) {
                YAHOO.util.Event.preventDefault(e);
                
                var shareURL,
                    shareURLWithTitle,
                    shareURLWithTitleAndURL,
                    eltarget = YAHOO.util.Event.getTarget(e);
                
                if (YAHOO.util.Dom.hasClass(eltarget, "share-widget-link")) {
                    //Get share url and replace placeholders with actual story details
                    shareURL                = YAHOO.util.Dom.getAttribute(eltarget, "href");
                    shareURLWithTitle       = shareURL.replace(/\{TITLE\}/, encodeURIComponent(activeStoryTitleNode.value));
                    shareURLWithTitleAndURL = shareURLWithTitle.replace(/\{URL\}/, encodeURIComponent(activeStoryURLNode.value));

                    //OK do the share redirect
                    window.location = shareURLWithTitleAndURL;
                }
            });
        }
    }();
    
    /**
    * Sets up the standard send widget.
    * 1) Include the send-widget.css file
    * 2) Add the button(s) as need with:
    * <a title="Title for share" href="http://intheknow.yahoo.com/blah/index.php?id=blah">
    *   <img class="share-widget" src="<?PHP CDN(); ?>images/share-widget/send_button.png" alt="share this" />
    * </a>
    * 3) Add the widget HTML just before the closing body:
    * <?PHP include "inc/widgets/send/send_widget.php"; ?>
    */
    YAHOO.bugsy.setupSendWidget = function() {
        //This setup function automatically sets up everything if there is any send widgets in the DOM
        if (!YAHOO.lang.isNull(YAHOO.util.Dom.get("send-widget-container"))) {
            var activeStoryTitleNode = YAHOO.util.Dom.get("active_send_story_title"),
                activeStoryURLNode   = YAHOO.util.Dom.get("active_send_story_url"),
                shareWidgetContainer = YAHOO.util.Dom.get("share-widget-container"),
                sendWidgetContainer  = YAHOO.util.Dom.get("send-widget-container");

            //We want to keep the send widgets portable and allow their events to work even if they are pulled and re-entered into the DOM
            YAHOO.util.Event.on(document, 'click', function(e) {
                var x, y, eltarget = YAHOO.util.Event.getTarget(e);
                
                if (YAHOO.util.Dom.hasClass(eltarget, "send-widget")) {
                    YAHOO.util.Event.preventDefault(e);

                    x = YAHOO.util.Dom.getX(eltarget);
                    y = YAHOO.util.Event.getPageY(e) + 15; //getPageY used to work around a Safari issue
                    shareWidgetContainer = YAHOO.util.Dom.get("share-widget-container");

                    //Make sure share is closed and activate send so there is no overlap
                    if (!YAHOO.lang.isNull(shareWidgetContainer)) {
                        YAHOO.util.Dom.addClass(shareWidgetContainer, "share-off");
                    }
                    YAHOO.util.Dom.removeClass(sendWidgetContainer, "share-off");
    
                    activeStoryTitleNode.value = YAHOO.util.Dom.getAttribute(eltarget.parentNode, "title");
                    activeStoryURLNode.value   = YAHOO.util.Dom.getAttribute(eltarget.parentNode, "href");

        		    YAHOO.util.Dom.removeClass("send-widget-container", "share-off");
        		    YAHOO.util.Dom.setXY("send-widget-container", [x, y]);
                }             
            });
            
            /* THIS PART CUSTOM TO INK */
            YAHOO.util.Event.on("send-page", 'click', function(e) {
                var eltarget = YAHOO.util.Event.getTarget(e);
                
                YAHOO.util.Event.preventDefault(e);

                var x = YAHOO.util.Dom.getX(eltarget) - 310,
                    y = YAHOO.util.Dom.getY(eltarget) + 15;

                YAHOO.util.Dom.removeClass("send-widget-container", "share-off");

                activeStoryTitleNode.value = YAHOO.util.Dom.getAttribute(eltarget, "title");
                activeStoryURLNode.value   = YAHOO.util.Dom.getAttribute(eltarget, "href");

    		    YAHOO.util.Dom.removeClass("send-widget-container", "share-off");
    		    YAHOO.util.Dom.setXY("send-widget-container", [x, y]);          
            });
            /* END CUSTOM INK */
            
            YAHOO.util.Event.on("send-widget-close", 'mouseover', function(e) {
                this.style.cursor = 'pointer';
            });
            
            //Handle widget close options
            YAHOO.util.Event.on('send-widget-close', 'click', function(e) {
                YAHOO.bugsy.closeSendWidget();
            });
            YAHOO.util.Event.on('send-widget-close-btn', 'click', function(e) {
                YAHOO.bugsy.closeSendWidget();
            });
            YAHOO.util.Event.on('send-widget-cancel', 'click', function(e) {
                YAHOO.bugsy.closeSendWidget();
            });
            
            //When a share network is selected we need to craft the proper share url
            YAHOO.util.Event.on('send_widget_submit', 'click', function(e) {
                YAHOO.util.Event.preventDefault(e);
                
                var shareURL,
                    shareURLWithTitle,
                    shareURLWithTitleAndURL,
                    eltarget         = YAHOO.util.Event.getTarget(e),
                    sendSubmitButton = YAHOO.util.Dom.get("send_widget_submit"),
                    swErrorRow       = YAHOO.util.Dom.get("send-widget-error-row");

                //Get share url and replace placeholders with actual story details
                var YUC          = YAHOO.util.Connect,
                    handleEvents = {
                        success : function(o) {
                            var responseObject = YAHOO.lang.JSON.parse(o.responseText);
                            
                            if (responseObject && responseObject.status === 'login_error') {
                                //Send them to the login with a redirect back here
                                YAHOO.bugsy.util.doYloginAndReturn();
                                return;
                            } else if (responseObject && responseObject.status === 'error') {
                                YAHOO.util.Dom.get("send-widget-error-msg").innerHTML = responseObject.message;
                                YAHOO.util.Dom.setStyle(swErrorRow, "display", "");
                            } else {
                                YAHOO.util.Dom.get("send_widget_story_sent").value = "yes";
                                YAHOO.util.Dom.setStyle("send-widget-success", "display", "block");
                                YAHOO.util.Dom.setStyle("send-widget-form", "display", "none");
                                YAHOO.util.Dom.get("send-widget-message-size").innerHTML = '250'; //reset
                            }
                        },
                        failure : function(o) {
                            YAHOO.util.Dom.get("send-widget-error-msg").innerHTML = "Unabled to send message!  Please try again.";
                            YAHOO.util.Dom.setStyle(swErrorRow, "display", "");
                        },
                        start  : function(o){
                            sendSubmitButton.disabled = true; //no double submit
                        },
                        complete : function(o){
                            sendSubmitButton.disabled = false;
                        },
                        timeout: 3000
                    };
                
                YAHOO.util.Connect.setForm(YAHOO.util.Dom.get("send-widget-form"));
                YUC.asyncRequest('post', "inc/widgets/send/send_widget_backend.php", handleEvents, null);
            });
        }
    }();
    
    //Allow widgets to be closed externally
    YAHOO.bugsy.closeShareWidget = function() {
        YAHOO.util.Dom.addClass("share-widget-container", "share-off");
    };   
    YAHOO.bugsy.closeSendWidget = function() {
        YAHOO.util.Dom.addClass("send-widget-container", "share-off");
        YAHOO.util.Dom.setStyle("send-widget-error-row", "display", "none"); //hide any old error messages
        YAHOO.util.Dom.get("send-widget-form").reset();

        //Reset form for reuse if they are closing after a successful send
        var storySentNode = YAHOO.util.Dom.get("send_widget_story_sent");
        if (storySentNode.value === 'yes') {
            YAHOO.util.Dom.setStyle("send-widget-success", "display", "none");
            YAHOO.util.Dom.setStyle("send-widget-form", "display", "block");
            storySentNode.value = 'no';
        }
    };
});