var $=jQuery.noConflict();

/*                                                              */try{/* doTimeout v0.4 - 7/15/2009 * http://benalman.com/projects/jquery-dotimeout-plugin/ *  * Copyright (c) 2009 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function($){var a={},c="doTimeout",d=Array.prototype.slice;$[c]=function(){return b.apply(window,[0].concat(d.call(arguments)))};$.fn[c]=function(){var f=d.call(arguments),e=b.apply(this,[c+f[0]].concat(f));return typeof f[0]==="number"||typeof f[1]==="number"?this:e};function b(k){var l=this,g,i={},m=arguments,h=4,f=m[1],j=m[2],o=m[3];if(typeof f!=="string"){h--;f=k=0;j=m[1];o=m[2]}if(k){g=l.eq(0);g.data(k,i=g.data(k)||{})}else{if(f){i=a[f]||(a[f]={})}}i.id&&clearTimeout(i.id);delete i.id;function e(){if(k){g.removeData(k)}else{if(f){delete a[f]}}}function n(){i.id=setTimeout(function(){i.fn()},j)}if(o){i.fn=function(p){o.apply(l,d.call(m,h))&&!p?n():e()};n()}else{if(i.fn){j===undefined?e():i.fn(j===false);return true}else{e()}}}})(jQuery);}catch(e){}


var bES=false;
var g_pathPrefix="";
if(location.pathname.substring(0, 14)=="/ACAFoundation"){g_pathPrefix="/ACAFoundation/";}else{g_pathPrefix="/";}
var sURL=window.document.location.href;
if (sURL.indexOf(".es.")>0){bES=true}else{bES=false};

/*
var mrseaves = {src: g_pathPrefix+'/assets/swf/mrseaves.swf', ratios: [8, 1.3, 11, 1.22, 12, 1.2, 18, 1.19, 23, 1.15, 25, 1.14, 28, 1.13, 39, 1.12, 61, 1.11, 94, 1.1, 95, 1.09, 103, 1.1, 107, 1.09, 110, 1.1, 119, 1.09, 120, 1.1, 1.09]};
sIFR.activate(mrseaves);
sIFR.replace(mrseaves,{selector: 'h3.callout',css: ['.sIFR-root {color:#659cd3; leading: 7; text-indent: 4; font-size: 26px;}'],wmode: 'transparent'});
*/
var images = new Array();
if (bES == false){
images.push(g_pathPrefix+'assets/pics/banner1.gif');
images.push(g_pathPrefix+'assets/pics/banner2.gif');
images.push(g_pathPrefix+'assets/pics/banner3.gif');
images.push(g_pathPrefix+'assets/pics/banner4.gif');
images.push(g_pathPrefix+'assets/pics/banner5.gif');
images.push(g_pathPrefix+'assets/pics/banner6.gif');
images.push(g_pathPrefix+'assets/pics/banner7.gif');
images.push(g_pathPrefix+'assets/pics/banner8.gif');
images.push(g_pathPrefix+'assets/pics/banner9.gif');
}
else{
images.push(g_pathPrefix+'assets/pics/banner1es.gif');
images.push(g_pathPrefix+'assets/pics/banner2es.gif');
images.push(g_pathPrefix+'assets/pics/banner3es.gif');
images.push(g_pathPrefix+'assets/pics/banner4es.gif');
images.push(g_pathPrefix+'assets/pics/banner5es.gif');
images.push(g_pathPrefix+'assets/pics/banner6es.gif');
images.push(g_pathPrefix+'assets/pics/banner7es.gif');
images.push(g_pathPrefix+'assets/pics/banner8es.gif');
images.push(g_pathPrefix+'assets/pics/banner9es.gif');
}
function stripTags(e){
	e = e.replace(/<title>.*<\/title>/,'')
	return  e.replace(/<\S[^>]*>/g, '');
}


function mailFriend(){
	window.open('friend.aspx?p='+cid,'sendwindow','status=0,toolbar=0,menubar=0,scrollbars=1,resizeable=0,width=570,height=400,location=0');
}

function limitChars(textid, limit, infodiv)
{
	var text = $('.'+textid).val();	
	var textlength = text.length;
	if(textlength > limit)
	{
	    if (bES==true){$('#' + infodiv).html('No puede escribir m·s de '+limit+' caracteres.')}
	    else{$('#' + infodiv).html('You cannot write more then '+limit+' characters.');}
		
		$('#'+textid).val(text.substr(0,limit));
		return false;
	}
	else
	{
	    if (bES==true){$('#' + infodiv).html(''+ (limit - textlength) +' caracteres sobrantes.')}
	    else{$('#' + infodiv).html(''+ (limit - textlength) +' Characters Remaining.')}
		return true;
	}
}
function printPage(){
	//play some peek-a-boo with ajax content
	if ($('#accordion').length){			
		var i=0;
		//peek!
		$('dt').each(function(){
			var theHref = $(this).find('a').attr('href');
			var theId = theHref.substring(theHref.indexOf('=')+1, theHref.indexOf(','));
			$(this).next('dd').load('/controls/content.aspx?cid='+theId+',12', function(){
				i++;
				if (i>=$('#accordion dt').length){
					/*$('dd').show();
					$('dd').css({
								'height':'0',
								'overflow':'hidden'
					});*/
					window.print();
					//a-boo!
					$(document).bind("focus mouseover", function(){
						$('dd').hide();
						$(this).unbind();
					});
				}
			});
			
		
		});
		
	}else{
		window.print();
	}
	
}
function boxit(target){
	var theText = $(target).text();
	var theHref = $(target).attr('href');
	$.facebox(function() {
		$.get(theHref, function(data) {
			data = stripTags(data);
			$('#facebox br').replaceWith('<span class="br"></span>');
			$.facebox('<h3>'+theText+'</h3>'+$.trim(data));
		})
	});
	
}
$(document).ready(function(){
    
    if ($("#ccCalc").length>0){
        $("#ccCalc").css("display","inline-block");
        /*
        $('.ccCalc-link').click(function(){
            var ctrl = $("#ccCalc");
            $.facebox(ctrl);
            $('#ccCalc *').each(function(){
                if(this.tagName.toLowerCase()!="input"){
                    $(this).show(1, function() {if($.browser.msie==true){this.style.removeAttribute('filter');} });
                }
            });
            ctrl.css("display","block");
            ctrl.focus();
            return false;
        });
        */
    }
    
    if ($("#cmCalc").length>0){
        $("#cmCalc").css("display","inline-block");
        /*
        $('.cmCalc-link').click(function(){
            var ctrl = $("#cmCalc");
            $.facebox(ctrl);
            $('#cmCalc *').each(function(){
                if(this.tagName.toLowerCase()!="input"){
                    $(this).show(10, function() {if($.browser.msie==true){this.style.removeAttribute('filter');} });
                }
            });
            ctrl.css("display","block");
            ctrl.focus();
            return false;
        });
        */
    }

    $.sitesearch();
	$('#ctl00_ContentPlaceHolder1_txtsender').css({'margin-top':'15px','margin-bottom':'0'});
	$('#ctl00_ContentPlaceHolder1_txtsender').keyup(function(event){
		if ($(this).attr('value') != ''){
			$('.your-name').html($(this).attr('value'));
		}else{
			$('.your-name').html('[your first name and last initial]');
		}
	});
	$('.def-link').click(function(){
		boxit($(this));
		return false;
	});
	$('.def-link').mouseover(function(){
		//var current = $(this);
		//var t = setTimeout(function(){boxit(current);}, 800);
	});
	$('#ctl00_ContentPlaceHolder1_txtreceiver').keyup(function(event){
		if ($(this).attr('value') != ''){
			$('.friends-name').html($(this).attr('value'));
		}else{
			$('.friends-name').html('[friend\'s name]');
		}
	});
	$('#mailer a').click(function(){
		opener.location.href = $(this).attr('href');
		return false;
	});
	var qs = window.location.search.substr(1);
	if($.browser['msie'] && $.browser['version'] < 7.0){
			$('#nav li:has(ul)').hover(
										  function(){
											this.getElementsByTagName('ul')[0].style.display = 'block';
										  },
										  function(){
											this.getElementsByTagName('ul')[0].style.display = 'none';
										  }
										  );
	}
	i=0;
	$('.tanbox').next('hr').css('display','none');
	$('#accordion.qa dt').each(function(){
			i++;
			$(this).replaceWith('<dt><span class="num">'+i+'. </span>' + $(this).html());
			
	});
	if (qs.indexOf('rvl=1')>=0){
		window.location='#qod';
		var theHref = $('#accordion dt:first-child a').attr('href');
		var theId = theHref.substring(theHref.indexOf('=')+1, theHref.indexOf(','));
		//alert (theId);
		if (bES==true){$('#accordion dt').append(' <span class="loader">[cargando]</span>').next().hide().wrapInner('<span class="pad"></span>')}
		else{$('#accordion dt').append(' <span class="loader">[loading]</span>').next().hide().wrapInner('<span class="pad"></span>')}
		$('#accordion dd').load('/controls/content.aspx?cid='+theId+',12', function(){
						$('.def-link').click(function(){
							boxit($(this));
							return false;
						});
						if ($('#accordion.qa').length || $('.tanbox').length){
							//alert ($('#accordion.qa'));
							if (!bES){$(this).prepend('<span class="title">Answer:</span>');}
							else{$(this).prepend('<span class="title">Respuesta:</span>');}
						}
						$('.loader').fadeOut('fast', function(){$(this).remove();});
						$('#accordion br').replaceWith('<span class="br"></span>');
						$('.open').removeClass('open').slideToggle('normal', function(){checking = false;});	
						$(this).addClass('open');
						$(this).slideToggle('normal', function(){checking = false;});
		});		
	}
	checking = false;
	$('#accordion dt').children('a').click(function(){
	
			if(!checking){
			
				checking = true;
				var theHref = $(this).attr('href');
				var theId = theHref.substring(theHref.indexOf('=')+1, theHref.indexOf(','));
				
				if($(this).parent('dt').next('dd').attr('class')!= 'open'){
				    
				    if (bES==true){$(this).parent('dt').append(' <span class="loader">[cargando]</span>')}
				    else{$(this).parent('dt').append(' <span class="loader">[loading]</span>')}
					$(this).parent('dt').next('dd').load('/controls/content.aspx?cid='+theId+',12', function(){
						$('.def-link').click(function(){
							boxit($(this));
							return false;
						});
						if ($('#accordion.qa').length || $('.tanbox').length){
							if (!bES){$(this).prepend('<span class="title">Answer:</span>');}
							else{$(this).prepend('<span class="title">Respuesta:</span>');}
						}
						$('.loader').fadeOut('fast', function(){$(this).remove();});
						$('#accordion br').replaceWith('<span class="br"></span>');
						$('.open').removeClass('open').slideToggle('normal', function(){checking = false;});	
						$(this).addClass('open');
						$(this).slideToggle('normal', function(){checking = false;});
					});		
				}else{
					$(this).parent('dt').next('dd').removeClass('open').slideToggle('normal', function(){checking = false;});
				}
			}
			return false;
			
	}).parent('dt').next().hide().wrapInner('<span class="pad"></span>');
	$('#accordion dt span').hover(
		function(){
			$(this).css('text-decoration', 'underline');
		},
		function(){
			$(this).css('text-decoration', 'none');
		}
	);
	//$('#qa dd').prepend('<span class="title">Answer:</span>');
	var col = 3;
	if ($('ul[class^="collumns"][class!="one"]').length){
		$('ul[class^="collumns"]').each(function(){
			var classes = $(this).attr('class').split(' ');
			//collumns = classes[$.inArray(/^collumns/, classes)];
			//alert (Math.classes);				
			var links = new Array();
			$('li',this).each( function(i, val){
				links.push(val);					  
			});
			
			links.sort(function(a, b){
				var keyA = $.trim($(a).text().toUpperCase());
				var keyB = $.trim($(b).text().toUpperCase());
				if (keyA < keyB) return -1;				
				if (keyA > keyB) return 1;
				return 0; 
			});
			var list = new String();
			var rows = Math.ceil(links.length/col);
			var bracket = new Array(col);
			//var final = new Array();
			for (i=0; i<col; i++){
				bracket[i] = new Array();
			}
			$(links).each(function(i, val){
				   bNum = Math.floor(i/rows);
				   bracket[bNum][i%rows] = $(val);
			});
			$(this).empty();
			for (i=0; i<col*rows; i++){
				if(typeof(bracket[i%col][Math.floor(i/col)]) != "undefined"){
					$(this).append(bracket[i%col][Math.floor(i/col)]);
				}else{
					$(this).append('<li>&nbsp;&nbsp;</li>');
				}
			}
		});
	}
	$('ol li').wrapInner('<span></span>');

	$('#crumbs .tier1:last-child a').css('background-position', 'right -297px');
	$('#crumbs .tier2:last-child a').css('background-position', 'right -270px');
	$('#crumbs .tier3:last-child a').css('background-position', 'right -243px');
	$('#crumbs .tier4:last-child a').css('background-position', 'right -216px');
	$('#crumbs .tier5:last-child a').css('background-position', 'right -189px');
	
	
	
	$('ul.anchors li:last-child').css({'border-right':'none', 'padding-right':'0'});
	$('ul.anchors li:first-child').css({'border-left':'none', 'padding-left':'0'});
	$('.question').keyup(function(){
		limitChars('question', 500, 'charlimitinfo');
	})
	if (bES==true){$('.question').after('<span id="charlimitinfo">Limite su pregunta a 500 caracteres o menos.</span>')}
	else {$('.question').after('<span id="charlimitinfo">Please limit your question to 500 characters or fewer.</span>')}
	//$('#content').prepend('<p id="corner-links"><a href="/email?page=<?=\'http://\'.$_SERVER[\'HTTP_HOST\'].$_SERVER[\'PHP_SELF\'] ?>">Email to a friend</a></p>');
	$('#qa dd:last-child').css('border-bottom','none');
	$('img').filter('.banner').length?$('img').filter('.banner')[0].src = images[Math.floor(Math.random()*images.length)]:null;
	if (bES==true){$('img').filter('.banner').length?$('img.banner').after('<p id="corner-links"><a href="#" onclick="printPage(); return false;">Imprima esta p&aacute;gina</a>&nbsp;|&nbsp;<a href="javascript:void(0)" onclick="mailFriend()">Env&iacute;e un correo electr&oacute;nico a un amigo</a></p>'):$('#content').prepend('<p id="corner-links"><a href="javascript:void(0)" onclick="printPage(); return false;">Imprima esta p&aacute;gina</a>&nbsp;|&nbsp;<a href="javascript:void(0)" onclick="mailFriend()">Env&iacute;e un correo electr&oacute;nico a un amigo</a></p>')}
	else{
	    $('p img.banner').css('margin-left','-70px');
	    if ($('img.banner').length>0){
	        $('img.banner').after('<p id="corner-links"><a href="#" onclick="printPage(); return false;">Print this page</a>&nbsp;|&nbsp;<a href="javascript:void(0)" onclick="mailFriend()">E-mail to a friend</a></p>');
	        $('img.banner').attr("alt","Ask Doctor Debt - Free Answers. Debt Solutions");
	    }
	    else{
	        $('#content').prepend('<p id="corner-links"><a href="javascript:void(0)" onclick="printPage(); return false;">Print this page</a>&nbsp;|&nbsp;<a href="javascript:void(0)" onclick="mailFriend()">E-mail to a friend</a></p>');
	    }
    }	    
	
	$.localScroll({duration:800});
	//}
});
$(window).load(function(){
	//alert ('loaded');
	
	for (var i=0; i<images.length; i++){
	$("<img>").attr("src", images[i]);}
});


/*
    $('.timer').countTo({
        from: -5000,
        to: 10000,
        time:1000,
        step:1,
        speed:100000,
        refreshInterval: 1,
        onComplete: function(value) {
        }
    });
*/
(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});
        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;
        return $(this).each(function() {
            var _this = this,loopCount = 0,value = options.from,interval = setInterval(updateTimer, options.refreshInterval);
            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));
                if (typeof(options.onUpdate) == 'function') {options.onUpdate.call(_this, value);}
                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;
                    if (typeof(options.onComplete) == 'function') {options.onComplete.call(_this, value);}
                }
            }
        });
    };
    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null  // callback method for when the element finishes updating
    };
})($);

$.sitesearch = function(){
    
    var loc = new String(window.location);  
    var host1 = new String('http://search.acainternational.org');
    var search;
    var searchButton;
    var inputCtrl = $("#q");
    
    if (bES!=true){searchButton='Search';search='/search?site=&client=drdebt_frontend&proxystylesheet=drdebt_frontend&output=xml_no_dtd&proxyreload=1&q=';}
    else{searchButton='Buscar';  search='/search?q=debt&client=drdebt_es_frontend&proxystylesheet=drdebt_es_frontend&output=xml_no_dtd&proxyreload=1&filter=0&q=';}
    var searchFrame = $('#search-frame1');
    searchFrame.attr('src', host1 + search); 
    $("#closesearch").click(function(){$('#searchresults').hide();$(inputCtrl).val(searchButton);return false;});
    $("#searchnow").click(function(){
        $.doTimeout(500, function(){
            if($(inputCtrl).attr("value").toString().length>0){
                var a = search + encodeURI($('#q').val());
                searchFrame.attr('src', host1 + a);
                $('#searchresults').slideDown(500, function() {
                    if($.browser.msie==true){this.style.removeAttribute('filter')}
                    searchFrame.css("height",'1100px');
                    $.doTimeout(100, function(){searchFrame.blur();
                    });
                });
            }
        });
    });
    
    $(inputCtrl).bind("keyup", function(e) {
        if($(inputCtrl).attr("value").toString().length>0){$("#searchnow").trigger("click");}
        return false;
    });
    $("#q").blur();
    $('#q').keypress(function(e){var code = null;code = (e.keyCode ? e.keyCode : e.which);if (code==13){return false;}});
    
}


/* util */
$.viewportHeight=function(){var h=0; if(typeof(window.innerHeight)=="number"){h=window.innerHeight;} else{ if(document.documentElement && document.documentElement.clientHeight){h=document.documentElement.clientHeight;} else{if(document.body && document.body.clientHeight){h=document.body.clientHeight;}} } return h;};
$.viewportWidth=function(){var h=0; if(typeof(window.innerWidth)=="number"){h=window.innerWidth;} else{ if(document.documentElement && document.documentElement.clientWidth){h=document.documentElement.clientWidth;} else{ if(document.body && document.body.clientWidth){h=document.body.clientWidth;} } } return parseInt(h);};
