var MultiLevelOpened;
/*
//Elimina los caracteres asentuados
String.prototype.replaceLatinChar = function(){
 return output = this.replace(/á|é|í|ó|ú|ñ|ä|ë|ï|ö|ü/ig,function (str,offset,s) {
        var str =str=="á"?"a":str=="é"?"e":str=="í"?"i":str=="ó"?"o":str=="ú"?"u":str=="ñ"?"ni":str;
		   str =str=="Á"?"A":str=="É"?"E":str=="Í"?"I":str=="Ó"?"O":str=="Ú"?"U":str=="Ñ"?"NI":str;
		   str =str=="Á"?"A":str=="É"?"E":str=="Í"?"I":str=="Ó"?"O":str=="Ú"?"U":str=="Ñ"?"NI":str;
		   str =str=="ä"?"a":str=="ë"?"e":str=="ï"?"i":str=="ö"?"o":str=="ü"?"u":str;
		   str =str=="Ä"?"A":str=="Ë"?"E":str=="Ï"?"I":str=="Ö"?"O":str=="Ü"?"U":str;
        return (str);
        })
	
}
*/

function ShowItemsOfClass(GadId, Id)
{
	if ((MultiLevelOpened !="undefined") && (MultiLevelOpened != GadId+Id)){
		$("#MLG"+MultiLevelOpened).hide("slow");
		$("#MLIG"+MultiLevelOpened).attr("src","/gadgets/contenidos/img/folder_close.png");
		MultiLevelOpened = GadId+Id;
	}else
	{
		if (MultiLevelOpened == GadId+Id)
			MultiLevelOpened = "undefined";
		else
			MultiLevelOpened = GadId+Id;
	}
	$("#MLG"+GadId+Id).toggle("slow");
	if ($("#MLIG"+GadId+Id).attr("src")=="/gadgets/contenidos/img/folder_open.png")
		$("#MLIG"+GadId+Id).attr("src","/gadgets/contenidos/img/folder_close.png");
	else
		$("#MLIG"+GadId+Id).attr("src","/gadgets/contenidos/img/folder_open.png");
}

function ChangeSrc(Id,NewSrc)
{
	$("#"+Id).attr("src",NewSrc);
}

//controler driver failer 

jQuery.fn.counter = function()
{
  $(this).each(function()
  {
        var max = $(this).attr('maxlength');
        var altMax = $(this).attr('altmaxlength');
        var val = $(this).attr('value').toString();
	    if (val.match("|||||||||||"))
		    max = altMax;
	    var cur = 0;
        if(val)
		   cur = val.length;
	    var Signature = $(this).attr('Signature');
	    var SignatureLarge = 0;
	    if (Signature)
		   SignatureLarge = Signature.length+1;

	    //Al primer mensaje le resto la firma
	    FirstMax = max - SignatureLarge;
	    if (FirstMax > cur )
	    {
		   //Es un unico mensaje
		   left = FirstMax - cur;
		   if (cur > 0)
			   msgCost = 1;
		   else
			   msgCost = 0;
		}
		else
		{
			cur = cur - FirstMax;
			mod = cur%max;
			left = max - mod;
			//Solo para limitar a un envio
			if (mod == 0)
				left = 0;
			//FIN
			msgCost = (cur - mod + FirstMax ) / max + 1;
			msgCost = msgCost.toFixed(0);
		}

      $("#Counter"+$(this).attr('name')).html(left.toString() + " caracteres restantes");
      $("#Cost"+$(this).attr('name')).html("Costo: $ "+ msgCost);

	if(left <= 3 && cur > 0)
	{
		$('#Counter'+$(this).attr('name')).removeClass('counter');
		$('#Counter'+$(this).attr('name')).addClass('counterWarning');
	}
	else
	{
		$('#Counter'+$(this).attr('name')).removeClass('counterWarning');
		$('#Counter'+$(this).attr('name')).addClass('counter');
	}
	if (cur == '' && val == '')
	{
		$(this).attr('value', 'Ingres aqu tu mensaje');
		$(this).addClass('SmsFormDisable');
	}
	$(this).keypress(function(i)
        {
        var val = $(this).attr('value').toString();
		if (val == 'Ingres aqu tu mensaje')
			$(this).attr('value', "");
		$(this).removeClass('SmsFormDisable');
		//Limito a 1 solo SMS
	    var Signature = $(this).attr('Signature');
	    var SignatureLarge = 0;
	    if (Signature)
		   SignatureLarge = Signature.length+1;
		if (val.match("|||||||||||"))
			max = $(this).attr('altmaxlength');
		else
			max =  $(this).attr('maxlength');
		maxLength = val.length + SignatureLarge;
        MaxMsgQty = $(this).attr('MaxMsgQty');
        if (!MaxMsgQty) MaxMsgQty = 4;

		if ((maxLength >= max * MaxMsgQty && i.keyCode != 8 && !(i.keyCode >= 33 && i.keyCode <= 40) && i.keyCode != 46 ))
		{
			return false;
		}
	});

	$(this).click(function(i)
        {
        var val = $(this).attr('value').toString();
		if (val == 'Ingres aqu tu mensaje')
		{
			$(this).attr('value', "");
			$(this).removeClass('SmsFormDisable');
		}
	});
	

	$(this).keyup(function(i)
    {
        var max = $(this).attr('maxlength');
        var altMax = $(this).attr('altmaxlength');
        var val = $(this).attr('value').toString();

	    if (val.match("|||||||||||") && altMax)
		    max = altMax;
	    var cur = 0;
        if(val)
		   cur = val.length;
	    var Signature = $(this).attr('Signature');
	    var SignatureLarge = 0;
	    if (Signature)
		   SignatureLarge = Signature.length+1;

	    //Al primer mensaje le resto la firma
	    FirstMax = max - SignatureLarge;
	    if (FirstMax > cur )
	    {
		   //Es un unico mensaje
		   left = FirstMax - cur;
		   if (cur)
			   msgCost = 1;
		   else
			   msgCost = 0;
		}
		else
		{
			cur = cur - FirstMax;
			mod = cur%max;
			left = max - mod;
			//Solo para limitar a un envio
			if (mod == 0)
				left = 0;
			//FIN
			msgCost = (cur - mod + FirstMax ) / max + 1;
			msgCost = msgCost.toFixed(0);
		}
	    if(left <= 5 && cur > 0)
	    {
			$('#Counter'+$(this).attr('name')).removeClass('counter');
			$('#Counter'+$(this).attr('name')).addClass('counterWarning');
		}
		else
		{
			$('#Counter'+$(this).attr('name')).removeClass('counterWarning');
			$('#Counter'+$(this).attr('name')).addClass('counter');
		}

		$("#Counter"+$(this).attr('name')).html(left.toString() + " caracteres restantes");
		$("#Cost"+$(this).attr('name')).html("Costo: $ "+ msgCost);
			
		return this;
    });
  });
  return this;
}

function cerrarModal(DivPrefix, GadgetId, Urls)
{
	$('#modalClose').click();
	if (DivPrefix && GadgetId)
	{
		RefreshGadget(DivPrefix, GadgetId, Urls);
	}
}

function DisableGadget(GadgetDivPrefix, GadgetId )
{
    var DivName = "gadget_content_"+GadgetDivPrefix;
    $("#"+DivName).css({opacity:'0.5'});
}

function EnableGadget(GadgetDivPrefix, GadgetId )
{
    var DivName = "gadget_content_"+GadgetDivPrefix;
    $("#"+DivName).css({opacity:'1'});
}

function RefreshGadget(GadgetDivPrefix, GadgetId, Urls, Func2Eval)
{
	if (!Urls)
		Urls = AccountDir+'/ajax/gadget.php?GId='+GadgetId+'&Action=reload';
	var DivName = "gadget_content_"+GadgetDivPrefix;
	$.ajax({
		type: "GET",
		url: Urls,
		beforeSend: function() {
			DisableGadget(GadgetDivPrefix, GadgetId);
		},
		success: function(DataRet){
			if( DataRet )
			{
				$("#"+DivName).html( DataRet );
                if (Func2Eval)
                    eval(Func2Eval);
				EnableGadget(GadgetDivPrefix, GadgetId);
				InitColorbox();
			}
		}
	 });
}

function ChangeBannerPref(BannerStatus)
{
	var Urls = AccountDir+'/ajax/gadget.php?Action=changepref&Type=account&Pref=TopBanner&Value='+BannerStatus;
	var DivName = "PublicidadAjaxDiv";
	RefreshAjaxDiv(DivName,Urls);
}

function ChangeBannerHeight(newHeight)
{
	$("#flashdiv").css({height: newHeight+'px'});
	$("#publicidad-movistar").css({height: newHeight+'px'});
//	document.getElementById('flashdiv').style.height=newHeight;
//	document.getElementById('publicidad-movistar').style.height=newHeight;
//alert("alto de la div: "+document.getElementById('publicidad-movistar').style.height);
	//$("div.flashdiv").animate({height:100}, "1");
}

function ChangeBannerStatus(parame)
{
// ChangeBannerPref('closed');
//	alert("open/close: "+parame);
}

function openAjaxDiv(DivId, CSSClass, UrlDir, CookieVar, CookieValue, ExpDays)
{
	ActCookieValue = false;
	if( CookieVar )
		ActCookieValue = $.cookie( CookieVar );

	if( ActCookieValue != CookieValue )
	{
		$.ajax({
		   type: "GET",
		   url: UrlDir,
		   success: function(DataRet){
		   			if( DataRet )
		   			{
		   				divObj = $("#"+DivId).attr("id");
		   				if( !divObj )
	   						$("body").prepend("<div id='"+DivId+"'></div>");
			  			if (CSSClass) $("#"+DivId).addClass(CSSClass);
						$("#"+DivId).hide();
			  			$("#"+DivId).html(DataRet).fadeIn("slow");
					}
			   }
		 });
	}
	SetCookie(CookieVar, CookieValue, ExpDays);
}

function SetCookie(CookieVar, CookieVal, DaysExp)
{
	if (CookieVar)
	{
		if (DaysExp)
		{
			$.cookie( CookieVar, CookieVal,{expires: DaysExp} );
		}
		else
		{
			$.cookie( CookieVar, CookieVal);
		}		
	}
}

function closeAjaxDiv( DivId, func2Exec )
{
	$("#"+DivId).html('').fadeOut("slow");

	if( func2Exec )
	{
		if( func2Exec.indexOf("(") )
			eval( func2Exec );
		else
			eval( func2Exec+'()');
	}
}

function openHelp(urlDir,cookieVar)
{
	openAjaxDiv("help", "", urlDir, cookieVar, "1");
}

function closeHelp( func2Exec )
{
	closeAjaxDiv( "help", func2Exec);
}

function refreshHelp(urlDir)
{
	$.ajax({
	   type: "GET",
	   url: urlDir,
	   success: function(DataRet){
		  		$("#help").html(DataRet);
		   }
	 });
}

function ChangeWelcomeHelpPref(Account,Show)
{
	var Status = 0;

	if( Show )
		Status = 1;

	var urlDir = '/'+Account+'/ajax/gadget.php?Action=changepref&Type=account&Pref=SkipWelcomePage&Value='+Status;

	$.ajax({
	   type: "GET",
	   url: urlDir,
	   success: function(DataRet){
	   			return;
//	   			alert("OK:"+ DataRet );
		   }
	 });
}

function DisableBrowserWarning(DivId, Account)
{
	var urlDir = '/'+Account+'/ajax/disable.php?Type=BrowserWarning';

	$.ajax({
	   type: "GET",
	   url: urlDir,
	   success: function(DataRet){
				$('#'+DivId).fadeOut();
		   }
	 });

}

function InitColorbox()
{
	$("img[rel='single']").colorbox({photo:true},function(){});
	$("img[rel='video']").colorbox({fixedWidth:"600px", fixedHeight:"400px", iframe:true, flv:true, showVideoFile: "/gadgets/album/video.php"});
	$("a[rel='SectionForm']").colorbox({fixedWidth:"500px", fixedHeight:"185px", iframe:true});
	$("a[rel='ItemForm']").colorbox({fixedWidth:"856px", fixedHeight:510, iframe:true});	
	$("a[rel='ShowInIframe']").colorbox({fixedWidth:"80%", fixedHeight:"550px", iframe:true});
	$("a[rel='login']").colorbox({fixedWidth:"600px", fixedHeight:"375px", iframe:true});
	$("a[rel='AlbumForm']").colorbox({fixedWidth:"605px", fixedHeight:"279px", iframe:true});
	$("a[rel='confirmAccount']").colorbox({fixedWidth:"605px", fixedHeight:"279px", iframe:true});
//	$("a[rel='masGadgets']").colorbox({fixedWidth:"605px", fixedHeight:"279px", iframe:false});
//	$("a[rel='theme']").colorbox({fixedWidth:"605px", fixedHeight:"279px", iframe:false});
}

function InitTockenInput()
{
    $(".SMSTokenInput").tokenInput(AccountDir+"/ajax/process.php?Gadget=sendsms&Method=suggestsending", {
        hintText: "Ingres el nmero de celular",
        noResultsText: "Sin resultados",
        searchingText: "Buscando...",
        minChars: 3,
        classes: {
            tokenList: "token-input-list-facebook",
            token: "token-input-token-facebook",
            tokenDelete: "token-input-delete-token-facebook",
            selectedToken: "token-input-selected-token-facebook",
            highlightedToken: "token-input-highlighted-token-facebook",
            dropdown: "token-input-dropdown-facebook",
            dropdownItem: "token-input-dropdown-item-facebook",
            dropdownItem2: "token-input-dropdown-item2-facebook",
            selectedDropdownItem: "token-input-selected-dropdown-item-facebook",
            inputToken: "token-input-input-token-facebook"
        }
    });
}

function CompleteUserData()
{
    UpdUserData = $.cookie( 'UpdUserData' );
    openedWelcome = $.cookie( 'openedWelcome' );

    if (UserUncomplettedData && !UpdUserData && (openedWelcome || WelcomeWinEnabled == 0))
    {
        SetCookie('UpdUserData', 1);
        $("a[rel='UpdateUserData']").colorbox({fixedWidth:"700px", fixedHeight:"540px", iframe:true}).click();
    }
}

function RefreshPageSection(Section)
{
    switch(Section)
    {
        case 'top':
            DivName = 'DivTop';
        break;
        default:
            return;
        break;
    }
    Url = AccountDir+'/ajax/layout.php?Action='+Section;
    $.ajax({
            type: "GET",
            url: Url,
            cache: false,
            success: function(DataRet){
                $("#"+DivName).html(DataRet);
            }
     });
}
//W = Warning E - Error T - Tips A - Advertiser
function LoadAlertMessage(Message,Type,Status,Time)
{
    ClassPrefix = "AlertMessage";
    DivContentMsgAlertTxt  ="MsgAlertTxt";
    DivContentMsgAlert = "ContentMsgAlert";
    //Tipo por defecto
    if (!Type)
        TypeClass = ClassPrefix+"T";
    else
        TypeClass = ClassPrefix+Type;
        
    if (Type == "E" || Type == "W"){
        DivContentMsgAlertTxt  = "FloatMsgAlertTxt";
        DivContentMsgAlert = "ContentFloatMsgAlert"; 
    }
    //Si viene mensaje! Lo cargo!
    if (Message)
        $("#"+DivContentMsgAlertTxt).html(Message);
    
    //Seteo la Clase segun el tipo de mensaje
    $("#"+DivContentMsgAlert).attr( "class",TypeClass);    
        
    //Muestro el Mensaje
    ToggleAlertMessage(Status, Type);
}

function ToggleAlertMessage(SetStatus, Type){
    //Botones
    BtnOn = "/images/grid/default/buttons_top_minimizeMsj.png";
    BtnOff = "/images/grid/default/buttons_top_maximizeMsj.png";
    
    DivContentMsgAlert = "ContentMsgAlert";
    var SetDelay2Reset = false;
    var OpenLastMsg = false;
    if (Type == "E" || Type == "W"){
        DivContentMsgAlert = "ContentFloatMsgAlert";
        SetDelay2Reset = "slow";
    }

    //Sino viene funciona como Toggle
    if (!SetStatus){
        if ($("#ContentMsgAlert").css("display") == "none")
            SetStatus = "Show";                                   
        else
            SetStatus = "Close";        
    }

    if (SetStatus=="Close"){
        $("#BtnShowHideMsgAlert").attr( "src", BtnOff);
        $("#"+DivContentMsgAlert).fadeOut("slow");
    }else{
        $("#"+DivContentMsgAlert).fadeIn("slow");
        if (SetDelay2Reset){
            if ($("#ContentMsgAlert").css("display") != "none"){
                OpenLastMsg = true;
                $("#ContentMsgAlert").fadeOut("slow");
            }
            setTimeout("DelayAlertMessage("+OpenLastMsg+")",20000);

            
            /*$("#"+DivContentMsgAlert).fadeOut(SetDelay2Reset, function() {
                // Animation complete.
                $("#"+DivContentMsgAlert).hide();
                if (OpenLastMsg)
                    $("#ContentMsgAlert").show();
              });*/
   
        }else
            $("#BtnShowHideMsgAlert").attr( "src", BtnOn);
    }
}

function DelayAlertMessage(OpenLastMsg){
    $("#ContentFloatMsgAlert").fadeOut('slow', function() {
    // Animation complete.
    if (OpenLastMsg)
        $("#ContentMsgAlert").fadeIn("slow");
  });
}


function RefreshUtilizeNav( Month2Show, DivName )
{
	Urls = AccountDir+'/ajax/utilize.php?Action=list&Month2Show='+Month2Show;

	$.ajax({
		type: "GET",
		url: Urls,
		beforeSend: function() {
			$("#"+DivName).css({opacity:'0.5'});
		},
		success: function(DataRet){
			if( DataRet )
			{
				$("#"+DivName).html( DataRet );
				$("#"+DivName).css({opacity:'1'});
			}
		}
	 });	
}

function DeleteProgrammedCommand( DelId, DelElement, DivName )
{
	Urls = AccountDir+'/ajax/programmedcommands.php?Action=delete&Id='+DelId;

	$.ajax({
		type: "GET",
		url: Urls,
		beforeSend: function() {
			$("#"+DivName).css({opacity:'0.5'});
		},
		success: function(DataRet){
			if( DataRet=="OK" )
			{
				$("#"+DelElement).fadeOut("slow");
			}
			$("#"+DivName).css({opacity:'1'});
		}
	 });
}

jQuery.fn.reset = function () {
  $(this).each (function() { this.reset(); });
}

function SubmitProgrammedCommandForm( FormName, DivName )
{
    if ($('#'+FormName).attr('action'))
        URL = AccountDir + $('#'+FormName).attr('action');
    else
        URL = document.location;
       
    var getUrl = URL + '&Data=' + escape($('#'+FormName).serialize());
    var Ret = $.ajax({
		url: getUrl,
		type: "GET",
		cache: false,
		beforeSend: function() {
			$("#"+DivName).css({opacity:'0.5'});
		},
		success: function (DataRet) {
			if( DataRet.substring(0,5) == 'ERROR' )
			{
				ErrorString = DataRet.substring(7);
				alert( ErrorString );
				$("#"+DivName).css({opacity:'1'});
			}
			else
			{
				$("#"+DivName).css({opacity:'1'});
				$("tr:first").fadeIn("slow").after( DataRet );
				$("#"+FormName).reset();
			}
		}
	});
	
	return false;
}



