﻿$(document).ready(function () {
    uploadMyPhoto();
    adminButtons();
    initForumForm();
    checkRemoveMe();
    initSendFile();
    faqQuestions();

    // external links and popups
    $("a[rel=external]").attr("target", "_blank");
    $("a[rel=popup]").click(function () {
        theHref = $(this).attr("href");
        $(this).attr("href", "javascript:void(0)");
        var popupWidth, popupHeight
        var relSplit = $(this).attr("rel").split("|");
        if (relSplit[1]) {
            popupWidth = relSplit[1];
            popupHeight = relSplit[2];
        } else {
            popupWidth = 435;
            popupHeight = 350;
        }
        popMeUp(theHref, popupWidth, popupHeight)
    });

    if ($('#tableLookAlike').length) {
        equalWidth();
        if ($.browser.msie && parseInt($.browser.version, 10) == 7) {
            toggleDropdown4IE7();
            $('#tableLookAlike li.tr:odd').css({ 'background-color': '#fff' });
        } else {
            toggleDropdown();
        }
    }


    // clear newsletter input


    // topTools


    $(".topTools .login li:first span").css("cursor", "pointer");
    $(".topTools .login li:first span").css("position", "absolute");
    $(".topTools .login li:first span").css("right", "6px");
    $(".topTools .login li:first span").css("top", "6px");
    $(".topTools .login li:first span").css("fontSize", "0.9em");
    $(".topTools .login li:first span").click(function () {
        $(".topTools .login").removeClass("active")
        $(".topTools .login ul:first").hide()
        $(".topTools .login ul:first li:first").hide()
    })

    $(".topTools .region a:first").click(function () {
        $(".topTools .language ul:first").hide()
        $(".topTools .region").css("zIndex", "10")
        $(".topTools .login").css("zIndex", "1")
        $(".topTools .login").removeClass("active")
        $(".topTools .region").toggleClass("active")
        $(".topTools .login ul:first").hide()
        $(".topTools .login ul:first li:first").hide()
        //$(".topTools .region ul").toggle()
        $(".topTools .region ul").slideToggle(200)
    })


    $(".topTools .login a:first").click(function () {
        $(".topTools .language").css("margin", "0");
        $(".topTools .language ul:first").hide()
        $(".topTools .region").css("zIndex", "1")
        $(".topTools .login").css("zIndex", "10")
        $(".topTools .region").removeClass("active")
        $(".topTools .login").toggleClass("active")
        $(".topTools .region ul:first").hide()
        //$(".topTools .region ul:first li:first").hide()
        $(".topTools .login ul:first").toggle()
        $(".topTools .login ul:first li:first").slideToggle(200)
    })

    $(".topTools .language a:first").click(function () {

        $(".topTools .login").css("zIndex", "1")
        $(".topTools .login").removeClass("active")
        $(".topTools .login ul:first").hide()
        $(".topTools .login ul:first li:first").hide()

        $(".topTools .region").css("zIndex", "1")
        $(".topTools .language").css("zIndex", "10")
        $(".topTools .login").css("zIndex", "1")
        $(".topTools .region").removeClass("active")

        $(".topTools .language").toggleClass("active")
        $(".topTools .region ul:first").hide()
        //$(".topTools .region ul:first li:first").hide()

        $(".topTools .language ul:first").slideToggle(200)
    })

    $('.expandableListCheckbox').click(function () {

        if ($('.XFormSalesForcePageInput').length != 0) {
            var inputTextValue = $('.XFormSalesForcePageInput').val();
            var array = inputTextValue.split(",");
            var checkboxValue = $(this).val();

            if ($(this).is(':checked')) {
                array.splice(array.length, 0, $(this).val())
            }
            else {
                var arLen = array.length;
                var index = -1;
                for (var i = 0, len = arLen; i < len; ++i) {
                    if (array[i] == checkboxValue) {
                        index = i;
                    }
                }
                if (index != -1) {
                    array.splice(index, 1);
                }
            }
            var arrayListValue = array.join(",");
            var startChar = arrayListValue.substr(0, 1);
            if (startChar == ",") {
                arrayListValue = arrayListValue.substr(1);
            }
            $('.XFormSalesForcePageInput').val(arrayListValue);
        }



    });

    //CasePortal
    $(".caseTableRow").click(function () {
        var url = (this).title;
        location.replace(url);
    })

    //	print
    if (window.print) {
        /*$("#printer").append('<p><img src="/UI/Images/icon.print.gif" /> Print this page</p>')*/
        /*$("#printer").css("cursor","pointer");*/
        $("#printer *").css("verticalAlign", "middle");
        /*$("#printer").click(function(){
        window.print();
			
        })*/
    }

    //eventChooser
    if ($("#eventChooser")) {
        var eventsLength = $("#eventChooser .eventTab").length;
        $("#eventChooser li").removeClass("active")
        $("#eventChooser li").removeClass("passive")
        $("#eventChooser li:eq(0)").addClass("active")
        var theId = $("#eventInfo:first .vevent:first input:first").val();
        $("#ctl00_FullRegion_MainRegion_EventId").val(theId);

        if ($("#eventInfo .vevent:first div").hasClass("falseForm")) {
            $(".showForm").hide();
        }
        if ($("#eventInfo .vevent:first div").hasClass("falseJobTitle")) {
            $(".jobTitle").hide();
        }

        $("#eventInfo .vevent").hide();
        $("#eventInfo .vevent:first").show(400);
        eventsContainer = $("#eventChooser")
        eventsList = $("#eventChooser ul:first");
        eventsList.css("width", (202 * eventsLength + 202) + "px")
        $("#eventWrap").append('<div id="clickBack" class="clickForward"></div><div id="clickBackArrow" class="clickForward"><img src="/UI/images/arrow.rew.26.gif" alt="&raquo" /></div>')
        $("#eventWrap").append('<div id="clickForward" class="clickBack"></div><div id="clickForwardArrow"" class="clickBack"><img src="/UI/images/arrow.ffw.26.gif" alt="&laquo" /></div>')
        var theIndex = 0
        $(".clickBack").click(function () {
            if (theIndex <= eventsLength - 2) {
                $("#clickBackArrow").show();
                firstEvent = theIndex
                secondEvent = theIndex + 1


                $("#eventChooser li:eq(" + firstEvent + ")").removeClass("active")
                $("#eventChooser li:eq(" + secondEvent + ")").addClass("active")

                eventsList.animate({
                    left: (0 - theIndex * 202) + "px"
                }, 400, "swing");
                $("#eventInfo .vevent").slideUp(400);
                var theId = $("#eventInfo:first .vevent:eq(" + secondEvent + ") input:first").val();
                $("#ctl00_FullRegion_MainRegion_EventId").val(theId);
                if ($("#eventInfo .vevent:eq(" + secondEvent + ") div").hasClass("trueForm")) {
                    if ($("#eventInfo .vevent:eq(" + secondEvent + ") div").hasClass("trueJobTitle")) {
                        $(".jobTitle").show();
                    } else {
                        $(".jobTitle").hide();
                    }
                    $(".showForm").show();
                    $(".formPanel").show();
                    $(".thankYouPanel").hide();
                    $(".errorPanel").hide();
                } else {
                    $(".showForm").hide();
                    $(".formPanel").hide();
                    $(".thankYouPanel").hide();
                    $(".errorPanel").hide();
                }
                $("#eventInfo .vevent:eq(" + secondEvent + ")").slideDown(400);
                theIndex++

            }
            if (theIndex >= eventsLength - 1) {
                $("#clickForwardArrow").css("display", "none");
            }
        });
        $(".clickForward").click(function () {
            if (theIndex >= 1) {
                $("#clickForwardArrow").css("display", "block");

                firstEvent = theIndex - 1;
                secondEvent = theIndex;

                $("#eventChooser li:eq(" + firstEvent + ")").addClass("active")
                $("#eventChooser li:eq(" + secondEvent + ")").removeClass("active")
                $("#eventInfo .vevent").slideUp(400);

                $("#eventInfo .vevent:eq(" + firstEvent + ")").slideDown(400);
                var theId = $("#eventInfo:first .vevent:eq(" + firstEvent + ") input:first").val();
                $("#ctl00_FullRegion_MainRegion_EventId").val(theId);
                if ($("#eventInfo .vevent:eq(" + firstEvent + ") div").hasClass("trueForm")) {
                    if ($("#eventInfo .vevent:eq(" + firstEvent + ") div").hasClass("trueJobTitle")) {
                        $(".jobTitle").show();
                    } else {
                        $(".jobTitle").hide();
                    }
                    $(".showForm").show();
                    $(".formPanel").show();
                    $(".thankYouPanel").hide();
                    $(".errorPanel").hide();
                } else {
                    $(".showForm").hide();
                    $(".formPanel").hide();
                    $(".thankYouPanel").hide();
                    $(".errorPanel").hide();
                }

                eventsList.animate({
                    left: (404 - theIndex * 202) + "px"
                }, 500, "swing");

                theIndex--

            }
            if (theIndex <= 0) {
                $("#clickBackArrow").css("display", "none");
            }

        });
    }


    //newsTicker
    if ($("#newsTicker")) {
        var newsLength = $(".newsTicker .single").length;
        newsContainer = $(".newsTicker")
        newsList = $(".newsTicker .news");
        $("#newsTicker .rew img").css("display", "none");

        newsContainer.css("overflow", "hidden")
        newsList.css("width", (193 * newsLength) + "px")
        $("#newsTicker .rew").css("width", "30px")
        $("#newsTicker .rew").css("height", "30px")
        $("#newsTicker .ffw").css("width", "30px")
        $("#newsTicker .ffw").css("height", "30px")

        var theIndex = 0
        $("#newsTicker .ffw img").click(function () {
            if (theIndex <= newsLength) {
                $("#newsTicker .rew img").fadeIn("200");



                newsList.animate({
                    left: ((0 - theIndex * 192) - 192) + "px"
                }, 800, "swing");

                theIndex++

            }
            if (theIndex >= newsLength - 3) {
                $("#newsTicker .ffw img").fadeOut("500");
            }
        });
        $("#newsTicker .rew img").click(function () {
            if (theIndex >= 1) {
                $("#newsTicker .ffw img").fadeIn("200");

                newsList.animate({
                    left: (192 - theIndex * 192) + "px"
                }, 800, "swing");

                theIndex--

            }
            if (theIndex <= 0) {
                $("#newsTicker .rew img").fadeOut("500");
            }

        });
    }

    $.objectWalk = function (obj, func, args) {
        var i,
			ar = args ? args : [];

        if (typeof func !== "function") {
            throw new Error("file: custom.js, Error: " + func + " is not a function");
        }
        func.apply(obj, ar);

        for (i in obj) {
            if (obj[i] && typeof obj[i] === "object" && (!obj[i].length && obj[i].length !== 0)) {
                $.objectWalk(obj[i], func, ar);
            }
        }
    };

    $.runAll = function () {
        var that = this,
			prop,
			obj;

        $.objectWalk(that, function () {
            if (this[arguments[0]]) {
                if (typeof this[arguments[0]] === "function") {
                    this[arguments[0]]();
                } else if (typeof this[arguments[0]] === "object" && (!this[arguments[0]].length && this[arguments[0]].length !== 0)) {
                    // this generates an Error in JSLInt:
                    // "Problem at line 41 character 26: Bad for in variable 'k'."

                    // I have no idea what it should be called to be a 'good one'.
                    // The 'k' variable is apparently ok in '$.objectWalk'...
                    obj = this[arguments[0]];
                    for (prop in obj) {
                        if (typeof obj[prop] === "function") {
                            obj[prop]();
                        }
                    }
                }
            }
        }, [arguments[0]]);
    };

    $.runInit = function (obj) {
        $.runAll.apply(obj, ["init"]);
    };

    //loadMap
    loadMap()

    //expandable
    expandable()
    expandable2()

});

function bookingForm(){
	$("#formBkg").css("height",$(document).height());
}
function loadMap(){
	$("#careerChooser li").hover(function(){
		$("span",this).fadeIn(200)
		$(this).css("zIndex",30)
	},
	function(){
		$("span",this).fadeOut(500)
		$(this).css("zIndex",1)
	})
}


function clearNewsInput(){
	var inputText = $("#ctl00_FullRegion_ctl02_txtEmail").val();
	$("#ctl00_FullRegion_ctl02_txtEmail").focus(function(){
		if($(this).val() == inputText){
			$(this).val("")
		}
	});
	$("#ctl00_FullRegion_ctl02_txtEmail").blur(function(){
		if(jQuery.trim($(this).val()) == ""){
			$(this).val(inputText)
		}
	});
	
}

function expandable(){
	$(".expandableList li h3").click(function(){
		if($("a", this).css("backgroundImage").indexOf("expanded") != -1) {
			$("a", this).css("backgroundImage", "url(/UI/Images/arrow.list.expand.gif)")
		} else {
			$("a", this).css("backgroundImage", "url(/UI/Images/arrow.list.expanded.gif)")
		}
		$(".expandable", this.parentNode).slideToggle(300)
		
	})
	clearNewsInput()
}


function expandable2() {
    $(".expandableListWithCheckbox li h3").click(function (e) {
        e.preventDefault();
        $(".expandable").hide(300);
        $(".expandableListWithCheckbox li a").css("font-weight", "normal");

        if (!$(this).next(".expandable").is(':visible')) { 
            $(this).next(".expandable").slideToggle(300);
            $("a", this).css("font-weight", "bold");
        }
    });

    clearNewsInput()
}

//infront script modified by Martin
function drawChart(){
	var theUrl = "http://www.infront-web.net/orc/iwt.dll/chart?width=600&height=300";
	theUrl += "&period="  + $(".chartShare:first select:first").val();
	theUrl += "&compare=SSE/SAX";
	$(".chartShare:first img:first").attr("src",theUrl);
}
function popMeUp(strURL,strWidth,strHeight) {
	theWin = window.open(strURL, 'popupWin', "scrollbars,resizable,height=" + strHeight + ",width=" + strWidth);
	theWin.focus()
}

/*

            function performPostBack(aTargetElement, aArg)
            {
                var postBack = new Sys.WebForms.PostBackAction();
                postBack.set_target(aTargetElement);
                postBack.set_eventArgument(aArg);
                postBack.performAction();
            }


*/

function uploadMyPhoto(){
	$(".changePhoto").click(function(){
		$(".uploadPhoto").toggle(400)
		return false;
	})

}
function adminButtons(){
    if($(".supportAdminTable").length > 0) {
    $.ajax({
        type: "GET",
        url: "/Common/Community/RegionGroups.ashx",
        dataType: "json",
        cache: false,
        success: function(data) {
	        theAreaDrop = '<select name="areas">'
            for(var i = 0; i < data.regions.length;i++) {
                theAreaDrop += '<option value="' + data.regions[i].regionId + '">' + data.regions[i].regionName + '</option>'
            }
           	theAreaDrop += '</select>'
        }
    });

	$(".supportAdminTable button, .supportAdminTable a.reset").click(function(){
		theCaseNumber =  jQuery.trim($(this).parents("tr").find(".caseNr").text())
		theCaseInput = '<input type="text" name="caseNumber" value="' + theCaseNumber + '">'

		if($(this).text()=="Edit"){
			$(this).text("Save");
			$(this).removeClass("saved");
			$(this).addClass("save");
			$(this).parents("tr").addClass("editing");
			theAreaOrig = $(this).parents("tr").find(".area").text();
			theAreaOrig = jQuery.trim(theAreaOrig);

			theCaseOrig = $(this).parents("tr").find(".caseNr").text();
			theCaseOrig = jQuery.trim(theCaseOrig);

			$(this).parents("tr").find(".area").html(theAreaDrop + '<span class="hider">' + theAreaOrig + '</span>');
			$(this).parents("tr").find(".caseNr").html(theCaseInput + '<span class="hider">' + theCaseOrig + '</span>');
			$(this).parents("tr").find(".hider").hide();
			$(this).parents("tr").find(".caseNr").find("input").css({width:"80px"});
			$(this).parents("td").append('<a href="#" class="reset">Cancel</a>')
			$(this).siblings("a").css("display","block")
			$(this).parents("td").find(".reset").click(function(){		
				$(this).parents("tr").find("button").text("Edit");
				$(this).parents("tr").find("button").removeClass("save");
				$(this).parents("tr").removeClass("editing");
			    theNewArea = $(this).parents("tr").find(".area").find(".hider").text();
				theNewCase = $(this).parents("tr").find(".caseNr").find(".hider").text();
				$(this).parents("tr").find(".area").text(theNewArea);
				$(this).parents("tr").find(".caseNr").text(theNewCase);
				$(this).remove();
				return false;
			})
			$(this).parents("tr").find(":text,select").keypress(function(e){
	            if (e.which == 13 ){
                    e.preventDefault()
                    var theButton = $(this).parents("tr").find("button");
		            var did = $(this).parents("tr").find(".did").val();
		            var rid = $(this).parents("tr").find(".area").find("select").val();
		            var cid = $(this).parents("tr").find(".caseNr").find("input").val();
		            var dataString = "did=" + did + "&rid=" + rid + "&cid=" + cid;
                    $.ajax({
                        type: "GET",
                        url: "/Common/Community/UpdateDocument.ashx",
                        dataType: "json",
                        cache: false,
                        data: dataString,
               
                        success: function(data) {
	                        theButton.parents("tr").find(".area").text(data.rName);
			                theButton.parents("tr").find(".caseNr").text(data.cid);
			                theButton.parents("td").find(".reset").remove()
			                theButton.text("Edit");
			                theButton.removeClass("save");
			                theButton.addClass("saved");
			                theButton.parents("tr").removeClass("editing");
                        }
                    });
        
            }
})	
			
		} else if($(this).text()=="Save"){
		    var theButton = $(this);
		    var did = theButton.parents("tr").find(".did").val();
		    var rid = theButton.parents("tr").find(".area").find("select").val();
		    var cid = theButton.parents("tr").find(".caseNr").find("input").val();
		    var dataString = "did=" + did + "&rid=" + rid + "&cid=" + cid;
            $.ajax({
                type: "GET",
                url: "/Common/Community/UpdateDocument.ashx",
                dataType: "json",
                cache: false,
                data: dataString,
               
                success: function(data) {
	                theButton.parents("tr").find(".area").text(data.rName);
			        theButton.parents("tr").find(".caseNr").text(data.cid);
			        theButton.parents("td").find(".reset").remove()
			        theButton.text("Edit");
			        theButton.removeClass("save");
			        theButton.addClass("saved");
			        theButton.parents("tr").removeClass("editing");
                }
            });
		}
	});
    }
}

function initTinyMCE(element){
    tinyMCE.init({
            mode : "exact",
            elements : element,
            language: "en",
            theme : "advanced",
            skin : "o2k7",
            plugins : "safari",

            theme_advanced_buttons1 : "bold,italic,|,link,unlink",
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            theme_advanced_buttons4 : "",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar : false,
            //theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : false,

            content_css : "",

            template_external_list_url : "lists/template_list.js",
            external_link_list_url : "lists/link_list.js",
            external_image_list_url : "lists/image_list.js",
            media_external_list_url : "lists/media_list.js"
        });
}
function initForumForm(){
    if($("#openForumForm").length > 0){
        $(".forumForm").hide();
        $("#openForumForm").click(function(){
            $(".forumForm").slideDown();
            $(".forumForm .mceLayout").css("width","600px");
            $(this).hide()
        });
        $(".forumForm .cancel").click(function(){
            $(".forumForm").slideUp(400,function(){
                $("#openForumForm").show();
            });
            return false;
        })
    }
}
function checkRemoveMe(){
    $(".removeMe .button,.confirmRemove").click(function(){
        if(!confirm("Are you sure? You can't undo this.")){ 
            return false;
        }
    });
}

function initSendFile(){
    $(".sendingFile").click(function(e){
       $("#updateProgressBox").css("display", "block");
    })
}
function faqQuestions(){
    var startTop = $(".faqQuestions").parent().offset().top, delay = (/(MSIE\s\d|Opera)/).test(navigator.userAgent) ? 10 : 50;
    if($(".faqQuestions").length > 0){
        $(window).scroll(function(){
            if($(window).scrollTop() > ($(".faqQuestions").parent().offset().top) + 20) {
                  $(".faqQuestions").animate({
                    top: ($(window).scrollTop()- startTop + 20) + "px"
                  },delay);
            } else {
                  $(".faqQuestions").animate({
                    top:"0px"
                  },delay);
            }

        });
    }
}
function HideError()
{
    $("#error").hide();
   }

// Show hide "dropdowns"
   function toggleDropdown() {
   	$('#tableLookAlike li.theTrigger').mouseover(function() {
   		var me = $(this);
   		if (me.children('ul').length) {
   			$('#tableLookAlike ul.p-dropDown').css({'visibility': 'hidden'});
   			$('#tableLookAlike a.opener').removeClass('active');
   			me.children('a.opener').addClass('active');
   			me.children('ul').css({'visibility': 'visible'});
   		}
   	});

	$('#tableLookAlike li.theTrigger').mouseout(function() {
		var me = $(this);
		if (me.children('ul').length) {
			$('#tableLookAlike ul.p-dropDown').css({ 'visibility': 'hidden' });
			$('#tableLookAlike a.opener').removeClass('active');
		}
	});
}


/**
*Hack for IE 7 which does not realize that the dropdown, when shown, is meant to go ON TOP of everything. 
* Instead it puts the ul underneath all other Elems, and you cant see it properly >_<
**/
function toggleDropdown4IE7(e, event) {
	$('#tableLookAlike li.theTrigger').mouseover(function(e, event) {
		//console.log('körs')
		if ($(this).children('ul').length) {
			// get the uls new poision
			var that = $(this),
				toMove = that.children('ul'),
				top = (that.offset().top) + 24,
				left = that.offset().left,
				a = that.children('a.opener');

			function trigDropDown() {
				that.attr('id', 'isBeingTrigd').addClass('trigd');
				that.children('a').addClass('active').attr('rel', 'trigd');
				that.children('ul').attr('id', 'trigd').find('a').addClass('trigd');

				// move the ul to the top of the body, set some css, run the close function
				$('body').prepend(toMove);
				toMove.css({ 'top': top, 'left': left, 'visibility': 'visible' });

				closeMe(e, event, toMove, a, that);
			}

			// make sure that no other dropdown is open, if they are the id="trigd" will be found, if not, add the id + classes "trigd" to the li its ul and its a tags
			if ($('#trigd').length) {

				$('#trigd').insertAfter($('#isBeingTrigd a.opener'));
				$('#trigd a').removeClass('trigd');
				$('#trigd').attr('id', '');

				$('#isBeingTrigd').children('a').removeClass('active').attr('rel', '');
				$('#isBeingTrigd').attr('id', '').removeClass('trigd');

				trigDropDown();

			} else {
				trigDropDown();
			}
		}
	});
}

/**
* for ie.
* Listen for mouseout and make sure that the elem your pointing at does not have id/class/rel ="trigd". If all OK, move the dropdown back to its original parent, li class="theTrigger".
* Then, remove classes/id/rel, unbind all events so they don't run forever, change the css.
**/
function closeMe(e, event, toMove, a, that) {
	var ul = toMove;

	// for the "dropdown ul"
	ul.mouseout(function(e) {
		$('body').mouseover(function(e) {
			if ((e.target.className !== 'trigd') && (e.target.rel !== 'trigd') && (e.target.id !== 'trigd')) {

				ul.insertAfter(a);
				ul.css({ 'top': '24px', 'left': '0px', 'visibility': 'hidden' });

				that.children('a').attr('rel', '').removeClass('active');
				ul.attr('id', '');
				ul.find('a').removeClass('trigd');
				that.removeClass('trigd');
				that.attr('id', '');

				$('body').unbind('mouseover');
				ul.unbind('mouseout');
			}
		});
	});
	
	// for the li wrapper
	that.mouseout(function(e) {		
		$('body').mouseover(function(e) {
			if ((e.target.className !== 'trigd') && (e.target.rel !== 'trigd') && (e.target.id !== 'trigd')) {				

				ul.insertAfter(a);
				ul.css({ 'top': '24px', 'left': '0px', 'visibility': 'hidden' });

				that.children('a').attr('rel', '').removeClass('active');
				ul.attr('id', '');
				ul.find('a').removeClass('trigd');
				that.removeClass('trigd');
				that.attr('id', '');

				$('body').unbind('mouseover');
				that.unbind('mouseout');
			}
		});
	});

	$('body').click(function() {

		$('#trigd').insertAfter($('#isBeingTrigd a.opener'));
		$('#trigd a').removeClass('trigd');
		$('#trigd').attr('id', '');

		$('#isBeingTrigd').children('a').removeClass('active').attr('rel', '');
		$('#isBeingTrigd').attr('id', '').removeClass('trigd');
	});
}

function equalWidth() {
    var span = $('#tableLookAlike li.tr > span'),
        widest = 0,
        thisWidth = 0;

        setEqHeight = function(elem) {
            widest = 0;
            elem.each(function() {
                thisWidth = $(this).outerWidth();

                if (thisWidth > widest) {
                    widest = thisWidth;
                    $('#tableLookAlike p.tHead > span').width((thisWidth+58));
                }
            });
            elem.css({ 'width': widest });
        }
    setEqHeight(span);
}

//validate form
$.fn.copyTo = function(to) {
    var to = $(to);
    for ( var i = 1; i < arguments.length; i++ )
        to.set( arguments[i], this.get(0)[ arguments[i] ] );
    return this;
};

new function() {
       // $.fn.validate = validate() {};
    $.fn.validate = {
        init: function(o) {
          if(o.name == 'email') { this.email(o) };
        },
        email: function(o) {
          var email  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;alert("yo!");
           if (o.value.match(email)) {
              doSuccess(o);
            } else {
              doError(o,'not a valid email');
            };
        }
        

     };
     

     function doSuccess(o) {
              $('#' + o.id + '_img').html('<img src="images/accept.gif" border="0" style="float:left;" />');
              $('#' + o.id + '_li').removeClass("error");
              $('#' + o.id + '_msg').html("");
              $('#' + o.id + '_li').addClass("success");
     }

     function doError(o,m) {
              $('#' + o.id + '_img').html('<img src="images/exclamation.gif" border="0" style="float:left;" />');
              $('#' + o.id + '_li').addClass("error");
              $('#' + o.id + '_msg').html(m);
              $('#' + o.id + '_li').removeClass("success");
     }
     //private helper, validates each type after check
     function doValidate(o) {
        	$('#' + o.id + '_img').html('<img src="images/loading.gif" border="0" style="float:left;" />');
        	$.post('ajax.php', { id: o.id, value: o.value }, function(json) {
                  	eval("var args = " + json);
                        if (args.success == true)
                  	{
                  	  doSuccess(args);
                  	}
                  	else
                  	{
                          doError(args,args.msg);
                  	}
                  });
    };

};
$.fn.match = function(m) {
	$('#' + this.get(0).id + '_img').html('<img src="images/loading.gif" border="0" style="float:left;" />');
	if ($(this).get(0).val() == $(m.match).val()) {
          $('#' + this.get(0).id + '_img').html('<img src="images/accept.gif" border="0" style="float:left;" />');
          $(m.error).removeClass("error");
          $(m.error).addClass("success");
          $('#' + this.get(0).id + '_msg').html("");
        } else {
          $('#' + this.get(0).id + '_img').html('<img src="images/exclamation.gif" border="0" style="float:left;" />');
          $(m.error).addClass("error");
          $(m.error).removeClass("success");
          $('#' + this.get(0).id + '_msg').html("The passwords don't match, please try again");
        };
       };

