/* this file now include also tooltip.js and motionpack.js */

function trans(tpl, itemt) {
	window.open('/index.php?section=trans&page=edit&tpl='+tpl+'&item='+itemt,"","scrollbars=yes,resizable=yes,status=no,location=no,toolbar=no,width=800,height=300");
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function createpoststring(){
    var emailvalue=document.getElementById("myform").EmailAddress.value //get value to post from a form field
    var email2value=document.getElementById("myform").EmailAddress2.value //get value to post from a form field
    var messagevalue=document.getElementById("myform").message.value //get value to post from a form field
    var titlevalue=document.getElementById("myform").title.value //get value to post from a form field
    var urlvalue=document.getElementById("myform").url.value //get value to post from a form field
    var poststr = "EmailAddress2=" + encodeURI(email2value) + "&EmailAddress=" + encodeURI(emailvalue) + "&title=" + encodeURI(titlevalue) + "&url=" + encodeURI(urlvalue) + "&message=" + encodeURI(messagevalue)
    return poststr
}

// This will make sure that if a tab is clicked before
// dom is ready, it will be displayed when dom becomes ready
// instead of the default one.
function waitForLoad( obj ) {
  window.tab2load = obj.rel;
}

$(document).ready(function() {
//FROM VIEW SITE INDEX

   $('a.poll_graph_button').toggle(function(){
	 $(this).next().next('div.graph_container').slideDown('slow');
	 },function(){
	 $(this).next().next('div.graph_container').slideUp('slow');
   });

	var tabContainers = $('div.tabs > div');
    tabContainers.hide().filter(this.hash).show();
	$('#popcodes').show();
	$('div.tabs ul.tabNavigation li:first').addClass('currenttab');

    $('div.tabs ul.tabNavigation a').not('.tab_disabled').click(function () {

        tabContainers.hide().filter('div.tabs div#'+this.rel).show();

        $('div.tabs ul.tabNavigation a').parent().removeClass('currenttab');
        $(this).parent().addClass('currenttab');

        return false;
    });

     $("ul.tabNavigation li a").hover(
             function(){
                     $(this).parent().addClass("hovertab");
             },
             function(){
                     $(this).parent().removeClass("hovertab");
             }
     );

    if ($("a.commentOnCode").length > 0) {
            $("a.commentOnCode").click(function() {
                    var id = $(this).attr('id');
                    $("#codeComments_"+id).load(siteURL+'index.php?section=code&action=ajax-list-comments&id='+id);
            })
    }


    jQuery.copy=function(t)//copy
    {
            if(typeof t=='undefined')
            {
                    t='';
            }

            if(t.createTextRange){
                    var tr = t.createTextRange();
                    if(tr)
                    tr.execCommand("Copy");
            }
            else
            {
                    d=document;
                    var f='flashcopier';
                    if(!d.getElementById(f))
                    {
                            var dd=d.createElement('div');
                            dd.id=f;
                            d.body.appendChild(dd);
                    }
                    d.getElementById(f).innerHTML='';
                    var i='<embed src="/public/js/copy.swf" FlashVars="clipboard='+encodeURIComponent(t)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
                    d.getElementById(f).innerHTML=i;
            }
    }

    if ($('#siteArea').length > 0) {
            $('#siteArea').change(function(){
                    window.location = $(this).find('option:selected').val();
            });
    }


    if ($("#searchFormField").length > 0) {
            $("#searchFormField").keypress(function() {
                    $("#searchResults").load('/user/search/'+$("#searchFormField").val(), null, function(){
                            $("#searchResultList li").click(function() {
                                    $('#searchFormField').val($(this).text());
                                    $('#resultId').val(this.id);
                                    $("#searchResults").empty();
                            });
                    });
            });

    }


    if($("a.toggle-email-alerts").length > 0) {
            $("a.toggle-email-alerts").click(function() {
                    var id = this.id;
                    $.ajax({
                    url: siteURL+'email-notification/change-alert/'+id,
                    type: 'GET',
                    timeout: 1000,
                    dataType: 'html',
                    error: function() {alert('Failed to Update.');},
                    success: function(text) {$("#"+id).text(text);}
                    })
            });
    }


//Poll Voting
    if($(".submit_vote").length > 0) {
            $(".submit_vote").click(function() {
                    var id = this.id;
                    $.ajax({
                            url: siteURL+'poll/ajax_vote/'+id,
                            type: 'POST',
                            timeout: 1000,
                            dataType: 'html',
                            data: {pollValue: $('input[name=option_'+id+']:checked').val()},
                            error: function() {alert('Could not vote on poll.');},
                            success: function(html) {
                                    $('#poll_results_'+id).fadeOut('slow', function(){
                                    $('#poll_results_'+id).html(html);
                                            $('#poll_results_'+id).fadeIn("slow");}
                                    );
                            }
                    })
            });
    }


//Expand/Collapse Div
    $('.expandLink').html('<img src="'+siteURL+'public/expand.png" alt="" title="Expand"> ');
    $('.expand').hide();
            $('.expandLink').click(function() {
                    $(this).parent().parent().next().slideToggle();
            });



//Vote On A Profile
    if ($("a.profile-vote").length > 0) {
            $("a.profile-vote").click(function() {

                    var id = this.id;
                    var profile = id.split('_');
                    var profileId = profile[1];

                    if(profile[0] == 'up') {
                            var URL = siteURL+'user/vote-up/'+profileId;
                    } else {
                            var URL = siteURL+'user/vote-down/'+profileId;
                    }

                    $.ajax({
                    url: URL,
                    type: 'GET',
                    timeout: 1000,
                    dataType: 'html',
                    error: function() {alert('Vote failed.');},
                    success: function(html) {$('span#voteid_'+profileId).html(html);}
                    });
            });
    }

    if($(".smileyClick").length > 0) {
            $(".smileyClick").click(function() {
                    var text = $("#postTextArea").val()+this.id;
                    $("#postTextArea").val(text);
            });
    }

});

function bookmarksite(title,url) {

    if (window.sidebar) { // firefox
            window.sidebar.addPanel(title, url, "");
    } else if (window.opera && window.print) { // opera
            var elem = document.createElement('a');
            elem.setAttribute('href',url);
            elem.setAttribute('title',title);
            elem.setAttribute('rel','sidebar');
            elem.click();
    } else if (document.all) {// ie
            window.external.AddFavorite(url, title);
    }
}


function CheckAll() {

    for (var i=0; i < document.posting.elements.length; i++) {
        var e = document.posting.elements[i];

            if ((e.name != 'allbox') && (e.type=='checkbox')) {
                    e.checked = document.posting.allbox.checked;
            }
    }

}

$(function(){
$(".code_listing .store a").mouseover(function(){
        $("span",$(this).parent()).show();
});
$(".code_listing .store a").mouseout(function(){
        $("span",$(this).parent()).hide();
});

//christmas giveaway banner
$(".code_listing .store a").mouseout(function(){
        $("span",$(this).parent()).hide();
});

$("#email","#christmas-giveaway").click(function(){
        return false;
});

$("#christmas-giveaway").click(function(){
        window.location = "/big-christmas-giveaway";
});



////////////////////////////////////////////////////////////////////////// More INFO ///////////////////////////////////////////////////////
$.fn.autoHeight = function(prop) {
        var temp = this.height();
        var result = this.height("auto").height();
        this.height(temp)
        return result;
};

//div#codes div.code_display a.more_info
$('div.more_info_container a.more_info').toggle(function(){
        var currentHeight;
        currentHeight = $(this).parent().prev().height();
        var newHeight = $(this).parent().prev().autoHeight();
        if( currentHeight < newHeight ){
                $(this).parent().prev().animate({height:''+newHeight+''});
                $(this).text(lessVar);
                //$(this).find('img').attr('src','public/images/js/red_arrow_up.jpg');
        }
},function(){
        $(this).parent().prev().animate({height: '4.5em'});
        //$(this).html("&darr;");
        $(this).text(moreVar);
        //$(this).find('img').attr('src','public/images/js/red_arrow_down.jpg');
});

//div#codes div.code_display p.description
$('p.shrunk_description').each(function(){
        var currentHeight;
        currentHeight = $(this).height();
        var autoHeight = $(this).autoHeight();
        if( autoHeight <= currentHeight ){
                $(this).height('auto');
                $(this).next().children().hide();
        }else{
                $(this).height('4.5em');
        }
});
////////////////////////////////////////////////////////////////////////// END More INFO ///////////////////////////////////////////////////////


});


$(function(){
   $('.autocomplete_off').attr('autocomplete','off');
});

function jumpTo(list) {

	if (list.options[list.selectedIndex].value != "home") {
		location = list.options[list.selectedIndex].value
	}

}

function createAjaxObj(){
var httprequest=false
if (window.XMLHttpRequest){ // if Mozilla, Safari etc
httprequest=new XMLHttpRequest()
if (httprequest.overrideMimeType)
httprequest.overrideMimeType('text/xml')
}
else if (window.ActiveXObject){ // if IE
try {
httprequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
httprequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return httprequest
}

var ajaxpack=new Object()
ajaxpack.basedomain="http://"+window.location.hostname
ajaxpack.ajaxobj=createAjaxObj()
ajaxpack.filetype="txt"
ajaxpack.addrandomnumber=0 //Set to 1 or 0. See documentation.

ajaxpack.getAjaxRequest=function(url, parameters, callbackfunc, filetype){
ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
if (ajaxpack.addrandomnumber==1) //Further defeat caching problem in IE?
var parameters=parameters+"&ajaxcachebust="+new Date().getTime()
if (this.ajaxobj){
this.filetype=filetype
this.ajaxobj.onreadystatechange=callbackfunc
this.ajaxobj.open('GET', url+"?"+parameters, true)
this.ajaxobj.send(null)
}
}

ajaxpack.postAjaxRequest=function(url, parameters, callbackfunc, filetype){
ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
if (this.ajaxobj){
this.filetype=filetype
this.ajaxobj.onreadystatechange = callbackfunc;
this.ajaxobj.open('POST', url, true);
this.ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
this.ajaxobj.setRequestHeader("Content-length", parameters.length);
this.ajaxobj.setRequestHeader("Connection", "close");
this.ajaxobj.send(parameters);
}
}

function processGetPost(){
var myajax=ajaxpack.ajaxobj
var myfiletype=ajaxpack.filetype
if (myajax.readyState == 4){ //if request of file completed
if (myajax.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
if (myfiletype=="txt")
alert(myajax.responseText)
else
alert(myajax.responseXML)
}
}
}


/* tooltip.js */

/* Copyright (c) 2008 Kean Loong Tan http://www.gimiti.com/kltan
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * Copyright notice and license must remain intact for legal use
 * jHelpertip
 * Version: 1.0 (Jun 2, 2008)
 * Requires: jQuery 1.2+
 */
(function($) {

	$.fn.jHelperTip = function(options) {
		// merge users option with default options
		var opts = $.extend({}, $.fn.jHelperTip.defaults, options);

		// default actions
		// create a ttC is not found
		if ($(opts.ttC).length == 0)
			$('<div id="'+opts.ttC.slice(1)+'"></div>').appendTo("body");

		// create a dC is not found
		if ($(opts.dC).length == 0)
			$('<div id="'+opts.dC.slice(1)+'"></div>').appendTo("body");

		if ($(opts.aC).length == 0)
			$('<div id="'+opts.aC.slice(1)+'"></div>').appendTo("body");


		// initialize our tooltip and our data container and also the close box
		$(opts.ttC).add(opts.aC).css({
			position: "absolute",
			display: "inline"
		}).hide();

		$(opts.dC).hide();

		// close the tooltip box
		var closeBox = function(){
			if (opts.source == "attribute")
				$(opts.aC).hide().empty();
			else
				$(opts.ttC).hide().empty();
		};

		$(".jHelperTipClose").bind("click", closeBox);
		$(opts.ttC).bind("mouseover",function(){
			$(opts.ttC).show();
			return false;
		});

		// the sources of getting data
		var getData = function(obj,e){
			if (opts.source == "ajax") {
				getPosition(e);
				$(opts.ttC).html('<div><img src="'+opts.loadingImg+'"/> '+opts.loadingText+'</div>').show();

				$.ajax({
					type: opts.type,
					url: opts.url,
					data: opts.data,
					success: function(msg){
						$(opts.ttC).html(msg);
						// reInitialize the close controller
						$(".jHelperTipClose").unbind("click", closeBox);
						$(".jHelperTipClose").bind("click", closeBox);
					}
				});
			}

			else if (opts.source == "container"){
				$(opts.ttC).show().empty();
				$(opts.dC).clone(true).show().appendTo(opts.ttC);
			}

			if (opts.source == "attribute"){
				$(opts.aC).html($(obj).attr(opts.attrName));
			}
		};

		// used to position the tooltip
		var getPosition = function (e){
			var top = e.pageY+opts.topOff;
			var left = e.pageX+opts.leftOff;

			if (opts.source == "attribute"){
				$(opts.aC).css({
					top: top,
					left: left,
					opacity: opts.opacity
				}).show();
			}
			else {
				$(opts.ttC).css({
					top: top,
					left: left,
					opacity: opts.opacity
				}).show();
			}
		};

		// just close tool tip when not needed usually trigger by anything outside out tooltip target
		if (opts.trigger == "hover") {
			$(this).bind("mouseover", function(e){
				e.preventDefault();
				getData(this, e);
				return false;
			});
			$(this).bind("mousemove", function(e){
				getPosition(e);
				return false;
			});

			$(this).bind("mouseout", function(e){
			    if (opts.source == "attribute")
					$(opts.aC).hide().empty();
				else
					$(opts.ttC).hide().empty();
				return false;
			});
		}

		else if (opts.trigger == "click") {
			$(this).bind("click", function(e){
				getData(this, e);
				getPosition(e);
				$(document).bind("click", function(e){
					if (opts.autoClose) {
						if (opts.source == "attribute")
							$(opts.aC).hide().empty();
						else
							$(opts.ttC).hide().empty();
					}
				});

				return false;
			});

		}
	};

	$.fn.jHelperTip.defaults = {
		trigger: "click",
		topOff: 3,
		leftOff: 10,
		source: "container", /* attribute, container, ajax */
		attrName: '',
		ttC: "#jHelperTipContainer", /* tooltip Container*/
		dC: "#jHelperTipDataContainer", /* data Container */
		aC: "#jHelperTipAttrContainer", /* attr Container */
		opacity:  1.0,
		loadingImg: "ajax-loader.gif",
		loadingText: "Loading...",
		type: "GET", /* data can be inline or CSS selector */
		//url: '',
		//data: '',
		autoClose: true
	};

})(jQuery);

/* motionpack.js */
var timerlen = 5;
var slideAniLen = 250;

var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();

function slidedown(objname){
        if(moving[objname])
                return;

        if(document.getElementById(objname).style.display != "none")
                return; // cannot slide down something that is already visible

        moving[objname] = true;
        dir[objname] = "down";
        startslide(objname);
}

function slideup(objname){
        if(moving[objname])
                return;

        if(document.getElementById(objname).style.display == "none")
                return; // cannot slide up something that is already hidden

        moving[objname] = true;
        dir[objname] = "up";
        startslide(objname);
}

function startslide(objname){
        obj[objname] = document.getElementById(objname);

        endHeight[objname] = parseInt(obj[objname].style.height);
        startTime[objname] = (new Date()).getTime();

        if(dir[objname] == "down"){
                obj[objname].style.height = "1px";
        }

        obj[objname].style.display = "block";

        timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
}

function slidetick(objname){
        var elapsed = (new Date()).getTime() - startTime[objname];

        if (elapsed > slideAniLen)
                endSlide(objname)
        else {
                var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
                if(dir[objname] == "up")
                        d = endHeight[objname] - d;

                obj[objname].style.height = d + "px";
        }

        return;
}

function endSlide(objname){
        clearInterval(timerID[objname]);

        if(dir[objname] == "up")
                obj[objname].style.display = "none";

        obj[objname].style.height = endHeight[objname] + "px";

        delete(moving[objname]);
        delete(timerID[objname]);
        delete(startTime[objname]);
        delete(endHeight[objname]);
        delete(obj[objname]);
        delete(dir[objname]);

        return;
}
function toggleSlide(objname){
  if(document.getElementById(objname).style.display == "none"){
    // div is hidden, so let's slide down
    slidedown(objname);
  }else{
    // div is not hidden, so slide up
    slideup(objname);
  }
}

   function submit_Poll(poll_id){

	 var id = 'cont_poll_'+poll_id;
	 var answer = $('#'+id+' :checked').attr('value');
	 var sec_code = $('#'+id+' input.sec_code').attr('value');

	 if(typeof answer != 'undefined'){//submit button clicked with nothing selected
	    $.ajax({
		  type: "POST",
		  url: "submit-poll",
		  data: 'poll_id='+poll_id+'&answer='+answer+'&sec_code='+sec_code,
		  success: function(response){
		    if( response != 0 ){
			  $('#'+id).animate({"height": "200px"}, "slow");
			  $('#'+id).html('<img src="'+response+'" alt="" title="" />');
		    }else{
			  //error
		    }
		  }
		});
	}

   }
