﻿/// <reference path="jquery-1.3.2.js" />

(function($) {

	// jQuery plugin definition
	$.fn.TextAreaExpander = function(minHeight, maxHeight) {

		var hCheck = !($.browser.msie || $.browser.opera);

		// resize a textarea
		function ResizeTextarea(e) {

			// event or initialize element?
			e = e.target || e;

			// find content length and box width
			var vlen = e.value.length, ewidth = e.offsetWidth;
			if (vlen != e.valLength || ewidth != e.boxWidth) {

				if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px";
				var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));

				e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
				e.style.height = h + "px"; 

				e.valLength = vlen;
				e.boxWidth = ewidth;
			}

			return true;
		};

		// initialize
		this.each(function() {

			// is a textarea?
			if (this.nodeName.toLowerCase() != "textarea") return;

			// set height restrictions
			var p = this.className.match(/expand(\d+)\-*(\d+)*/i);
			this.expandMin = minHeight || (p ? parseInt('0'+p[1], 10) : 0);
			this.expandMax = maxHeight || (p ? parseInt('0'+p[2], 10) : 99999);

			// initial resize
			ResizeTextarea(this);

			// zero vertical padding and add events
			if (!this.Initialized) {
				this.Initialized = true;
				$(this).css("padding-top", 0).css("padding-bottom", 0);
				$(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea);
			}
		});

		return this;
	};

})(jQuery);


// initialize all expanding textareas
jQuery(document).ready(function() {
	jQuery("textarea[class*=expand]").TextAreaExpander();
});


jQuery.LoadScript = function(doc, source) {
    var p = doc.getElementsByTagName("HEAD")[0];
    var c = doc.createElement("script");
    c.type = "text/javascript";
    c.src = source;
    p.appendChild(c);
}

jQuery.preloadImages = function() {
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

function replaceURLWithHTMLLinks(text) {
    var exp = /([^"]\b(http|https|ftp|file):\/\/(?!www\.youtube\.com|i4.ytimg.com)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
    //if (text != undefined && text.toString().indexOf("www.youtube.com") == -1)
        //alert(text.replace(exp, "$1"));
        return text.replace(exp, "<a target=\"_blank\"  href='/external/?url=$1'>$1</a>");
   // else
    //    return text;
}

function replaceURLWithVideo(text) {
    var exp = /(\bhttp:\/\/www\.youtube\.com\/watch\?v=[-A-Z0-9+&@#\/%=~_|]*)/gi;
    var matches = text.match(exp);
    if (matches != null) {
        for (var i = 0; i < matches.length; i++) {
            var link = matches[i]; 
            if (link != undefined) {
                var start = link.indexOf("watch?v=") + "watch?v=".length;
                link = link.substring(start);

                var end = link.indexOf("&") == -1 ? link.length : link.indexOf("&");
                link = link.substring(0, end);

                var video = '<br>  &nbsp;<img src="/global/img/youtube.gif" /> &nbsp; <b>YouTube</b> <br> <a class="thickbox youtube" href="http://www.youtube.com/embed/' + link + '?autoplay=0&KeepThis=true&TB_iframe=true&height=400&width=600"><img src="http://i4.ytimg.com/vi/' + link + '/default.jpg" /><img class="play" src="/global/img/play.gif" /></a>';

                text = text.replace(matches[i], video);
            }
        }
    }
    return text
}

function closeEditorWarning() {
    return 'It looks like you have been editing something -- if you leave before submitting your changes will be lost.'
}
function unsaved(bool) {
    if (bool)
        window.onbeforeunload = closeEditorWarning;
    else
        window.onbeforeunload = null;
}


function urlToYouTube(textarea, preview) {

    function replaceYouTube(text) {
        
        if (text.toString().toLowerCase().indexOf("http://www.youtube") != -1) {

            $(preview).html("");
            var exp = /(\bhttp:\/\/www\.youtube\.com\/watch\?v=[-A-Z0-9+&@#\/%=~_|]*)/gi;
            var matches = text.match(exp);
            for (var i in matches) {

                var link = matches[i];
                var start = link.indexOf("watch?v=") + "watch?v=".length;
                link = link.substring(start);

                var end = link.indexOf("&") == -1 ? link.length : link.indexOf("&");
                link = link.substring(0, end);

                //$("#Previews").html('<iframe class="youtube-player" type="text/html" width="470" height="283"  src="http://www.youtube.com/embed/'+ link +'" frameborder="0"></iframe>')
                $(preview).append('  &nbsp;<img src="/global/img/youtube.gif" /> &nbsp; <b>YouTube</b> <br> <a class="thickbox youtube" href="http://www.youtube.com/embed/' + link + '?autoplay=0&KeepThis=true&TB_iframe=true&height=400&width=600"><img src="http://i4.ytimg.com/vi/' + link + '/default.jpg" /><img class="play" src="/global/img/play.gif" /></a>')

            }

            tb_init('a.thickbox');
        }

    }

    $(textarea).keyup(function() { replaceYouTube($(this).val()); });

}





function GetSurvey() { 
    
      var newwindow;

      function poptastic(url) {
          url = url.toString();
          if (url.indexOf("/") > -1) {
              url = url.substr(url.lastIndexOf("/") + 1);
          }
          newwindow = window.open(url, 'name', 'height=600,width=600,resizable=yes, left=150, top=150, scrollbars=yes');
          if (window.focus) { newwindow.focus(); }
      }
    
       var snip = "<div class='snip'><h1></h1><h2></h2> <div class='body'><div class='pitch'></div> <div style='text-align:center;'><a class='surveylink button' style='padding:10px; border:3px solid #ccc' target='_blank' href='' ><div style='padding:10px;' >Start Survey</div></a></div> </div> </div> ";
      
       $(snip).appendTo("body").hide();
       var domsnip = $(".snip");
       
       
       $.get("/getsurvey/", null, function(msg) {  
          
      // alert(msg);

           
          // $("body").append(  $(msg).text()  );
          //$("body").append(  "<br>" +  $("name", msg).text() ); 
          //$("body").append(  "<br>" +  $("ipitch", msg).text().length ); 
          
          //show new survey
          if ($("pitch", msg).text().length > 0){

              domsnip.find(".pitch").html($("pitch", msg).text().replace("\n", "<br /><br />"));
            domsnip.find(".surveylink").attr('href', "/survey/?sid="+$("sid", msg).text()+"&survey="+$("survey", msg).text()+"&name="+$("name", msg).text());
            domsnip.find("h1").text( $("title", msg).text() )  ; 
            domsnip.find("a").click(function() {
              poptastic($(this).attr('href'));
              return false;
            });

            $.jGrowl($(".snip").html(), { sticky: true, theme: "note" }); 
            
          }
          
          //look for old surveys
          if ($("ipitch", msg).text().length > 0 && $("isurvey", msg).text() != $("survey", msg).text()){

              domsnip.find(".pitch").html($("ipitch", msg).text().replace("\n", "<br /><br />"));
            domsnip.find(".surveylink").attr('href', "/survey/?sid="+$("sid", msg).text()+"&survey="+$("isurvey", msg).text()+"&name="+$("name", msg).text());
            domsnip.find("h2").text( $("ititle", msg).text() )  ; 
            domsnip.find("h1").text( "Finish This Survey" )  ; 
            //domsnip.find(".startsurvey").addClass("resumesurvey").removeClass(".startsurvey");
            domsnip.find("a").click(function() {
              poptastic($(this).attr('href'));
              return false;
            });

            $.jGrowl($(".snip").html(), { sticky: true, theme: "note" }); 
             
            
          }
          
           $(".jGrowl-notification a").click(function() {   $(this).closest(".close").click();  });
          
       },($.browser.msie ? "xml" : "html")); 
    }


var tools = {

    autoEllipseText: function(element, text, width) {
        $("body").append('<div id="ellipsisSpan"><span style="white-space:nowrap;">' + text + '</span></div>');
        inSpan = $('#ellipsisSpan');
        if (inSpan.width() > width) {
            var i = 1;
            inSpan.text('');
            while (inSpan.width() < (width) && i < text.length) {
                inSpan.text(text.substr(0, i) + '...');
                i++;
            }

            var returnText = inSpan.text();
            if (returnText.lastIndexOf(" ") > 0) {
                returnText = returnText.substr(0, returnText.lastIndexOf(" ")) + '...';
            }
            inSpan.remove();
            return returnText;
        }
        inSpan.remove();
        return text;
    }
,
    alphanumeric: function(alphane) {
        var numaric = alphane;
        for (var j = 0; j < numaric.length; j++) {
            var alphaa = numaric.charAt(j);
            var hh = alphaa.charCodeAt(0);
            if ((hh > 47 && hh < 58) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123)) {
            }
            else {
                return false;
            }
        }
        return true;
    }
    ,
    CheckCount: function() {
 
        $(".charLimit").keyup(function() {
            if (!this.id) this.id = $(this).attr('id');
            var id = this.id;
            var limitval = $("#" + id + "Limit span").text()
            if (!this.limit) { this.limit = parseInt(limitval); }
            //var limit = parseInt($("#" + id + "Limit span").text());
            if ($(this).val().length >= this.limit) {
                $("#" + id + "Chars").addClass("overLimit").text($(this).val().length);
                $(this).val($(this).val().substr(0, this.limit -1)); 
            }
            else {
                if (!this.chars) {this.chars =$("#" + id + "Chars"); }
                this.chars.removeClass("overLimit").text($(this).val().length);
            }
        }).keyup();
    }
}




function ErrorBoxes() {
    var error = $("#Error");
    if (error.text() == "") { error.hide(); } else { error.show(); }
}

function RunInits() {
    if (typeof (inits) !== 'undefined') {
        jQuery.each(inits, function(i) {
            eval(inits[i]);
        });
    }
}

function MouseOver(Item, Enter, Leave) {
    $(Item).bind("mouseenter", Enter).bind("mouseleave", Leave); 
}

function MatchHeight(classes) {
    //var maxheight = 0;
    //$(classes).each(function() { if ($(this).height() > maxheight) maxheight = $(this).height(); }).each(function() { if ($(this).height() < maxheight) { $(this).height(maxheight); } });
    function equalHeight(group) {
        tallest = 0;
        group.each(function() {
            thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.height(tallest);
    }

    equalHeight($(classes));
}

function Buttons() {
    $(".button").each(function() {
    var id = $(this).attr("id");
    var clas = $(this).hasClass("multibutton") ? "multibutton" : "";
    $(this).removeClass("multibutton");
        $(this).removeAttr("id");
        $(this).wrap('<div id="' + id + '" class="posthover buttonBox "><div class="buttonleft '+clas+'"><div class="buttonright "></div></div></div>');
    });
}
function Hover() {
    //Buttons();

    var elems = new Array();
    elems.push("hover");
    elems.push("buttonhover"); 
    $.each(elems, function() {
        var selector = this.toString();
        MouseOver(".pre" + selector, function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); });
        MouseOver(".post" + selector, function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); });
        MouseOver("." + selector, function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); });
        $(".pre" + selector + ", ." + selector + ", .post" + selector).removeClass("pre" + selector).removeClass("post" + selector).removeClass(selector); 
    });
    MouseOver(".button", function() { $(this).addClass("buttonhover"); }, function() { $(this).removeClass("buttonhover"); });
    MouseOver(".altbutton", function() { $(this).addClass("altbuttonhover"); }, function() { $(this).removeClass("altbuttonhover"); });
    MouseOver(".cancelbutton", function() { $(this).addClass("cancelbuttonhover"); }, function() { $(this).removeClass("cancelbuttonhover"); }); 
}


function PopupCenter(pageURL, title, w, h) {
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2); 
    var targetWin = window.open(pageURL, title, 'scrollbars=no, resizable=no, menubars=no,location=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
    //window.open(url, 'name', 'height=600,width=600,resizable=yes, left=150, top=150, scrollbars=yes');
}

$().ready(function() {

//    $('a.tip').tooltip({
//        track: true,
//        delay: 0,
//        showURL: false,
//        showBody: " - ",
//        fade: 250
//    });


    $("a.ShareIt").click(function() {
    PopupCenter("http://www.facebook.com/share.php?u=http://www.partnerup.com" + $(this).attr('href'), "ShareonFacebook", 800, 480); 
        return false;
    });


    //highight selected nav item
    var section = $("body").attr('page');
    $("#PrimaryNav a").removeClass("selected")
    $("#PrimaryNav a." + section).addClass("selected");



    //    $('.button, .altbutton, .cancelbutton').corners("transparent no-native");
    //    $('.rtop').corners("transparent no-native top");

    jQuery.each(jQuery.browser, function(i, val) {
        if (i == "mozilla" && jQuery.browser.version.substr(0, 3) == "1.9") {
            $('.prnd').corners("transparent");
        }

    });

    //$('li ul').corners("bottom transparent");

    DD_roundies.addRule('.button, a.altbutton, .rounded, .IABButton2, #Sponsor300, .Error, .Warning, .Msg', '5px', true);
    DD_roundies.addRule('.smallcorners', '3px', true);
    DD_roundies.addRule('.bigcorner', '9px', true);
    DD_roundies.addRule('.Cap, .rtop', '3px 3px 0px 0px', true);
    DD_roundies.addRule('.Plug, .UnPlug, .End, .rbottom', '0px 0px 3px 3px', true);

    Hover();

    //$("div.js").removeClass("js");
    //$("#Search").focus(function() { $(this).val(""); $(this).css({ "color": "#000", "font-style": "normal" }); });

    $(".example").focus(function() { if ($(this).hasClass("example")) { $(this).removeClass("example").val(""); } });
    //    $(".example").each(function() {
    //        var example = $(this);
    //        var val = example.val();
    //        $(this).closest("form").submit(function() {
    //            alert("test");
    //            if ($(this).find(".example").val() == val) {
    //                $(this).find(".example").val("");
    //            }
    //        });
    //    });
    var tt = 1;
    $(".button").click(function() {
        $(".example").val("");

    });


    //TJK(); 

    RunInits();

    //space to enter buttons
    $("a").keyup(function(event) { if (event.keyCode == 32) { $(this).click(); } });

    //last
    $("div.ImageLeft, div.ImageLeftBlurb").find(".item:last").addClass("last");

    tools.CheckCount();

    $(".fav a").click(function() {
        $.get($(this).attr("href"), function(data) {
            if ($(".Error, .Msg", data).text().length > 0)
                $.jGrowl($(".Error, .Msg", data).text());
        });
        $(this).closest(".fav").toggleClass("favorite");
        $(".fav").fadeOut(function() { $(".fav").fadeIn(); });
        return false;
    });

    $(".MarkSpam").click(function() {
        $.get($(this).attr("href"), function(data) {
            if ($(".Error, .Msg", data).text().length > 0)
                $.jGrowl($(".Error, .Msg", data).text());
        });
        $(this).addClass("hover");
        return false;
    });

    $(".vote a").live('click', function() {
        //if (confirm('test')) {
        var vote = $(this).closest(".vote");
        var votesid = $(this).closest(".utils").find("b.votes").attr('id');
        $.get($(this).attr("href") + "&ajax=1", function(data) {
            if ($(".Error, .Msg", data).text().length > 0) {
                if ($(".Error, .Msg", data).text().indexOf("Please") == -1) {
                    $(vote).closest(".utils").find(".vote").not(vote).removeClass("voted");
                    vote.toggleClass("voted");
                    vote.fadeOut("fast", function() { vote.fadeIn(); });

                }
            }
            $.jGrowl($(".Error, .Msg", data).text());
            $("#" + votesid).text($("#" + votesid, data).text());
        });
        return false;
    });


    $(".MsgGrowl").each(function() {
        $.jGrowl($(this).html(), {
            sticky: true,
            theme: "note"//,
            //  beforeOpen: function() { $(".wrap, .leftCol").fadeTo('fast', 0.3); },
            //  beforeClose: function() { $(".wrap, .leftCol").fadeTo('fast', 1); }
        });
    });



    //    $("#topnav").dropSlideMenu({
    //        //indicators: true, // adds a div to the list items for attaching indicators (arrows)
    //        clickstream: true, // highlights the clickstream in a menu by comparing the links to the current URL path
    //        //openEasing: "easeOutQuad", // open animation effect
    //        //closeEasing: "easeInQuad", // close animation effect
    //        duration: 600, // speed of drop down animation (in milliseconds)
    //        delay: 400, // delay before the drop down closes (in milliseconds)
    //        hideSelects: true // hide all select elements on the page when the menu is active (IE6 only)
    //    });


    if ($.autocomplete) {
        $(".LocationAC").autocomplete("/misc/location/");
    }

    $(".loadConv").click(function() {
        var newconv = this;

        $.get($(newconv).attr("href"), function(data) {
            var parent = $(newconv).parent().parent().siblings(".ResBox");
            $(newconv).parent().parent().hide();
            parent.html($(".Responses", data).reverse().html()).find(".msgDash, .repnumber, .Reply").remove();
            AjaxPersonTip(parent);

        });

        return false;
    });





});


function AjaxPersonTip(domain) {
    $("a[href^=/Person][href$=/]", domain).addClass("tip ajaxtip").attr('title', ' - ');
    $("a[href^=/Person][title=''][href$=/]", domain).attr('title', ' - ');
    $('a.ajaxtip', domain).tooltip({
        track: false,
        delay: 0,
        showURL: false,
        showBody: " - ",
        fade: 250
    });
}






