var params;
Function.prototype.method = function (A, B) {
    this.prototype[A] = B;
    return this
};

window.sutter = window.sutter || {};
sutter.augmentObject = function (B, C) {
    for (var A in C) {
        B[A] = C[A]
    }
    return B
};


$.fn.isSigninMenu = function () {
	return this.each(function () {
		var menuNode = $(this);
		var successNode = menuNode.find(".toggleText");
		successNode.addClass("hide");
		
		var button = menuNode.closest(".popupParent").find('.signin');
		var bOffset = button.offset();
		menuNode.css({
	    top: bOffset.top + button.height(),
	    left: bOffset.left -menuNode.width() + button.width()
	  });
	  
	  
		//handles button clicks on the "open form" link
		button.click(function (e) {

			//var B = $(this);

			//close all open menus
			$(".signin_menu").not(menuNode).hide();
			//remove all class tags of menu open
			$('.signin').not(button).removeClass("menu-open");

			successNode.removeClass("show");
	    
			menuNode.toggle();
	    button.toggleClass("menu-open");
	    return(false);
	  });
	 
	 //turns off event bubbling to event clicks on the form 
	 menuNode.mouseup(function () {
	  	return false
	  });
	  
	  //handles document mouseclicks
		$(document).mouseup(function (e) {
			if ($(e.target).parents('.signin').length == 0) {
	  		button.removeClass("menu-open");	
				successNode.removeClass("show"); 
			  menuNode.hide();

			}

		});

	  //handles the "submit" button clicks
		menuNode.find(".clickA").click(function (B) {
			if ($(B.target).parent("a.signin").length == 0) {
				
					
				var form = $(this).closest('form');
				var nameInputPar = form.find('input[name=title]').parent();
				var linkInputPar = form.find('input[name=link]').parent();
						
				//get field values
				var params = form.serializeArray();  				
							
				//if it's a new script
				if(form.hasClass('submitScript')) {					
					//AJAX
					$.post( 'submitScript.php',  params, function(data, status) { 
						var response = JSON.parse(data);
						if(!response.valid) {
							//mark invalid fields
							if(response.noTitle){
								nameInputPar.css('background-image', 'url(images/textFWSred.gif)');
							}
							if(response.noURL){
								linkInputPar.css('background-image','url(images/textFWSred.gif)');
							}
						}
						else {
							form.clearForm();
							nameInputPar.css('background-image', 'url(images/textFWS.gif)');
							linkInputPar.css('background-image','../images/textFWS.gif');
							successNode.addClass('show');
						}
					}, 'JSON' );
				}
				//if it's an edit
				else if (form.hasClass('editScript')) {					
					//push the key of the row into the POST var
					var sk = menuNode.closest('.result').attr('id');				
					params.push({'name': 'sk', 'value': sk});
						
					$.post( 'editScript.php',  params, function(data, status) { successNode.show(); }, 'text' );
				}
					 							
			}
			return false
		});
		
		//handles the "close after submit" button clicks
		menuNode.find(".clickB").click(function (B) {
			if ($(B.target).parent("a.signin").length == 0) {
				$(".signin").removeClass("menu-open");	
				successNode.removeClass("show"); 
					
				$(".ssl_con").removeClass("show");
			      	menuNode.hide();				
		    }
			
		});
	});
};

function reportLink(e) {
	var target = $(e.target);
	if (!target.hasClass('report-link')) 
		target = target.closest('.report-link');
	rID = target.attr('id').substr(7);	
	jQuery.post( 
		'deadlink.php', 
		{ rowID : rID }, 
		function(data, status) { 
			if (status="success") { 
				target.find('img').attr('src','images/thanks.gif'); 
			} 
		}, 
		'text' 
	); 
	
}

$.fn.clearForm = function() {
  return this.each(function() {
 var type = this.type, tag = this.tagName.toLowerCase();
 if (tag == 'form')
   return $(':input',this).clearForm();
 if (type == 'text' || type == 'password' || tag == 'textarea') {
   this.value = '';
   this.focus();
   this.blur();
 }
 else if (type == 'checkbox' || type == 'radio')
   this.checked = false;
 else if (tag == 'select')
   this.selectedIndex = -1;
  });
};

//on load, setup the forms
$(function () {
  $(".signin_menu").isSigninMenu();	
  
  $('.report-link').click(reportLink);
});

/* Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.0.3
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */
(function ($) {

    $.extend($.fn, {
        livequery: function (type, fn, fn2) {
            var self = this,
                q;

            // Handle different call patterns
            if ($.isFunction(type)) fn2 = fn,
            fn = type,
            type = undefined;

            // See if Live Query already exists
            $.each($.livequery.queries, function (i, query) {
                if (self.selector == query.selector && self.context == query.context && type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid))
                // Found the query, exit the each loop
                return (q = query) && false;
            });

            // Create new Live Query if it wasn't found
            q = q || new $.livequery(this.selector, this.context, type, fn, fn2);

            // Make sure it is running
            q.stopped = false;

            // Run it immediately for the first time
            q.run();

            // Contnue the chain
            return this;
        },
        expire: function (type, fn, fn2) {
            var self = this;

            // Handle different call patterns
            if ($.isFunction(type)) fn2 = fn,
            fn = type,
            type = undefined;

            // Find the Live Query based on arguments and stop it
            $.each($.livequery.queries, function (i, query) {
                if (self.selector == query.selector && self.context == query.context && (!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped) $.livequery.stop(query.id);
            });

            // Continue the chain
            return this;
        }
    });
    $.livequery = function (selector, context, type, fn, fn2) {
        this.selector = selector;
        this.context = context || document;
        this.type = type;
        this.fn = fn;
        this.fn2 = fn2;
        this.elements = [];
        this.stopped = false;
        // The id is the index of the Live Query in $.livequery.queries
        this.id = $.livequery.queries.push(this) - 1;
        // Mark the functions for matching later on
        fn.$lqguid = fn.$lqguid || $.livequery.guid++;
        if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;
        // Return the Live Query
        return this;
    };
    $.livequery.prototype = {
        stop: function () {
            var query = this;
            if (this.type)
            // Unbind all bound events
            this.elements.unbind(this.type, this.fn);
            else if (this.fn2)
            // Call the second function for all matched elements
            this.elements.each(function (i, el) {
                query.fn2.apply(el);
            });
            // Clear out matched elements
            this.elements = [];
            // Stop the Live Query from running until restarted
            this.stopped = true;
        },
        run: function () {
            // Short-circuit if stopped
            if (this.stopped) return;
            var query = this;
            var oEls = this.elements,
                els = $(this.selector, this.context),
                nEls = els.not(oEls);
            // Set elements to the latest set of matched elements
            this.elements = els;
            if (this.type) {
                // Bind events to newly matched elements
                nEls.bind(this.type, this.fn);
                // Unbind events to elements no longer matched
                if (oEls.length > 0) $.each(oEls, function (i, el) {
                    if ($.inArray(el, els) < 0) $.event.remove(el, query.type, query.fn);
                });
            } else {
                // Call the first function for newly matched elements
                nEls.each(function () {
                    query.fn.apply(this);
                });
                // Call the second function for elements no longer matched
                if (this.fn2 && oEls.length > 0) $.each(oEls, function (i, el) {
                    if ($.inArray(el, els) < 0) query.fn2.apply(el);
                });
            }
        }
    };
    $.extend($.livequery, {
        guid: 0,
        queries: [],
        queue: [],
        running: false,
        timeout: null,
        checkQueue: function () {
            if ($.livequery.running && $.livequery.queue.length) {
                var length = $.livequery.queue.length;
                // Run each Live Query currently in the queue
                while (length--)
                $.livequery.queries[$.livequery.queue.shift()].run();
            }
        },
        pause: function () {
            // Don't run anymore Live Queries until restarted
            $.livequery.running = false;
        },
        play: function () {
            // Restart Live Queries
            $.livequery.running = true;
            // Request a run of the Live Queries
            $.livequery.run();
        },
        registerPlugin: function () {
            $.each(arguments, function (i, n) {
                // Short-circuit if the method doesn't exist
                if (!$.fn[n]) return;
                // Save a reference to the original method
                var old = $.fn[n];
                // Create a new method
                $.fn[n] = function () {
                    // Call the original method
                    var r = old.apply(this, arguments);
                    // Request a run of the Live Queries
                    $.livequery.run();
                    // Return the original methods result
                    return r;
                }
            });
        },
        run: function (id) {
            if (id != undefined) {
                // Put the particular Live Query in the queue if it doesn't already exist
                if ($.inArray(id, $.livequery.queue) < 0) $.livequery.queue.push(id);
            } else
            // Put each Live Query in the queue if it doesn't already exist
            $.each($.livequery.queries, function (id) {
                if ($.inArray(id, $.livequery.queue) < 0) $.livequery.queue.push(id);
            });

            // Clear timeout if it already exists
            if ($.livequery.timeout) clearTimeout($.livequery.timeout);
            // Create a timeout to check the queue and actually run the Live Queries
            $.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
        },
        stop: function (id) {
            if (id != undefined)
            // Stop are particular Live Query
            $.livequery.queries[id].stop();
            else
            // Stop all Live Queries
            $.each($.livequery.queries, function (id) {
                $.livequery.queries[id].stop();
            });
        }
    });

    // Register core DOM manipulation methods
    $.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');

    // Run Live Queries when the Document is ready
    $(function () {
        $.livequery.play();
    });


    // Save a reference to the original init method
    var init = $.prototype.init;

    // Create a new init method that exposes two new properties: selector and context
    $.prototype.init = function (a, c) {
        // Call the original init and save the result
        var r = init.apply(this, arguments);

        // Copy over properties if they exist already
        if (a && a.selector) r.context = a.context,
        r.selector = a.selector;

        // Set properties
        if (typeof a == 'string') r.context = c || document,
        r.selector = a;

        // Return the result
        return r;
    };

    // Give the init function the jQuery prototype for later instantiation (needed after Rev 4091)
    $.prototype.init.prototype = $.prototype;

})(jQuery);
/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.metadata.js 3640 2007-10-11 18:34:38Z pmclanahan $
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are four supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *          
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *   
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *   html5: Values are stored in data-* attributes.
 *          
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @example <p id="one" class="some_class" data-item_id="1" data-item_label="Label">This is a p</p>
 * @before $.metadata.setType("html5")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a series of data-* attributes
 *
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function ($) {

    $.extend({
        metadata: {
            defaults: {
                type: 'class',
                name: 'metadata',
                cre: /({.*})/,
                single: 'metadata'
            },
            setType: function (type, name) {
                this.defaults.type = type;
                this.defaults.name = name;
            },
            get: function (elem, opts) {
                var settings = $.extend({},
                this.defaults, opts);
                // check for empty string in single property
                if (!settings.single.length) settings.single = 'metadata';

                var data = $.data(elem, settings.single);
                // returned cached data if it already exists
                if (data) return data;

                data = "{}";

                var getData = function (data) {
                    if (typeof data != "string") return data;

                    if (data.indexOf('{') < 0) {
                        data = eval("(" + data + ")");
                    }
                }

                var getObject = function (data) {
                    if (typeof data != "string") return data;

                    data = eval("(" + data + ")");
                    return data;
                }

                if (settings.type == "html5") {
                    var object = {};
                    $(elem.attributes).each(function () {
                        var name = this.nodeName;
                        if (name.match(/^data-/)) name = name.replace(/^data-/, '');
                        else return true;
                        object[name] = getObject(this.nodeValue);
                    });
                } else {
                    if (settings.type == "class") {
                        var m = settings.cre.exec(elem.className);
                        if (m) data = m[1];
                    } else if (settings.type == "elem") {
                        if (!elem.getElementsByTagName) return;
                        var e = elem.getElementsByTagName(settings.name);
                        if (e.length) data = $.trim(e[0].innerHTML);
                    } else if (elem.getAttribute != undefined) {
                        var attr = elem.getAttribute(settings.name);
                        if (attr) data = attr;
                    }
                    object = getObject(data.indexOf("{") < 0 ? "{" + data + "}" : data);
                }

                $.data(elem, settings.single, object);
                return object;
            }
        }
    });

    /**
     * Returns the metadata object for the first member of the jQuery object.
     *
     * @name metadata
     * @descr Returns element's metadata object
     * @param Object opts An object contianing settings to override the defaults
     * @type jQuery
     * @cat Plugins/Metadata
     */
    $.fn.metadata = function (opts) {
        return $.metadata.get(this[0], opts);
    };

})(jQuery); //Licensed under The MIT License
//Copyright (c) 2008 Jason Frame (jason@onehackoranother.com)

(function ($) {
    $.fn.tipsy = function (opts) {

        opts = $.extend({
            fade: false,
            gravity: 'n'
        },
        opts || {});
        // ...Added by andy@twitter.com 20090717
        if (!opts['offsetTop']) {
            opts['offsetTop'] = 0;
        }
        if (!opts['offsetLeft']) {
            opts['offsetLeft'] = 0;
        }
        if (!opts['header']) {
            opts['header'] = '';
        }
        if (!opts['footer']) {
            opts['footer'] = '';
        }
        if (!opts['hideTimeout']) {
            opts['hideTimeout'] = 100;
        }
        if (!opts['showTimeout']) {
            opts['hideTimeout'] = 0;
        }
        if (!opts['additionalCSSClass']) {
            opts['additionalCSSClass'] = '';
        }
        var showTimeoutKey = false;
        // ...Added by andy@twitter.com 20090717
        var tip = null,
            cancelHide = false;
        this.hover(function () {

            // ...Added by andy@twitter.com 20090717
            var linkText = $(this).text();
            var header = opts['header'].replace('%{link}', linkText);
            var footer = opts['footer'].replace('%{link}', linkText);
            // ...Added by andy@twitter.com 20090717
            $.data(this, 'cancel.tipsy', true);

            var tip = $.data(this, 'active.tipsy');
            if (!tip) {
                $('.tipsy').hide();
                tip = $('<div class="tipsy ' + opts['additionalCSSClass'] + '"><div class="tipsy-inner">' + header + $(this).attr('title') + footer + '</div></div>');
                tip.css({
                    position: 'absolute',
                    zIndex: 100000
                });
                $(this).attr('title', '');
                $.data(this, 'active.tipsy', tip);
                // Added by rael@twitter.com 20090628...
            } else if ($(this).attr('title') != '') {
                tip.find('.tipsy-inner').html($(this).attr('title'));
                $(this).attr('title', '');
                // ...Added by rael@twitter.com 20090628
            }

            var pos = $.extend({},
            $(this).offset(), {
                width: this.offsetWidth,
                height: this.offsetHeight
            });
            // ...Added by andy@twitter.com 20090717
            pos.top = pos.top + opts['offsetTop'];
            pos.left = pos.left + opts['offsetLeft'];

            // remove open tips if timeout to fade
            $('.tipsy').hide();
            // ...Added by andy@twitter.com 20090717
            tip.remove().css({
                top: 0,
                left: 0,
                visibility: 'hidden',
                display: 'block'
            }).appendTo(document.body);
            var actualWidth = tip[0].offsetWidth,
                actualHeight = tip[0].offsetHeight;

            switch (opts.gravity.charAt(0)) {
            case 'n':
                tip.css({
                    top: pos.top + pos.height,
                    left: pos.left + pos.width / 2 - actualWidth / 2
                }).addClass('tipsy-north');
                break;
            case 'l':
                //left north align
                tip.css({
                    top: pos.top + pos.height,
                    left: pos.left + pos.width / 2 - 18
                }).addClass('tipsy-north');
                break;
            case 's':
                tip.css({
                    top: pos.top - actualHeight,
                    left: pos.left + pos.width / 2 - actualWidth / 2
                }).addClass('tipsy-south');
                break;
            case 'e':
                tip.css({
                    top: pos.top + pos.height / 2 - actualHeight / 2,
                    left: pos.left - actualWidth
                }).addClass('tipsy-east');
                break;
            case 'w':
                tip.css({
                    top: pos.top + pos.height / 2 - actualHeight / 2,
                    left: pos.left + pos.width
                }).addClass('tipsy-west');
                break;
            }
            // ...Added by andy@twitter.com 20090717


            function show() {
                if (opts.fade) {
                    tip.css({
                        opacity: 0,
                        display: 'block',
                        visibility: 'visible'
                    }).animate({
                        opacity: 1
                    });
                } else {
                    tip.css({
                        visibility: 'visible'
                    });
                }
            }
            if (opts['showTimeout']) {
                showTimeoutKey = setTimeout(show, opts['showTimeout']);
            } else {
                show();
            }
        },


        function () {
            clearTimeout(showTimeoutKey);
            // ...Added by andy@twitter.com 20090717
            $.data(this, 'cancel.tipsy', false);
            var self = this;
            setTimeout(function () {
                if ($.data(this, 'cancel.tipsy')) return;
                var tip = $.data(self, 'active.tipsy');
                if (opts.fade) {
                    tip.stop().fadeOut(function () {
                        $(this).remove();
                    });
                } else {
                    tip.remove();
                }
            },
            opts['hideTimeout']);
        });

    };
})(jQuery);