/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

 
YAHOO.util.Event.onDOMReady( eco_Main);
YAHOO.util.Event.onDOMReady( eco_AdminUserProfil);

function eco_Main(){

    //debugger;
    var imgs = document.getElementsByTagName('img');

    var widgetImg=null;

    for(var a=0;a<imgs.length;a++){
        if ( typeof (imgs[a].id) != 'undefined') {
              if (imgs[a].id.indexOf('acvu_widget')!=-1) {
                  widgetImg = imgs[a];
                  break;
              }
        }
    }

    if(widgetImg==null)return;


    var arId = widgetImg.id.split('_');
    var acvuId = arId[0]+'_'+arId[1];

    var imgBtn = document.getElementById('bbAddVideo');

    if(imgBtn==null) return;

    var fnc = function() {
    
        showAcvuPanel(acvuId+'_pannel',acvuId);

    }

    var pannel = document.getElementById(acvuId+'_pannel');
    if(pannel==null) return;

    pannel.parentNode.removeChild(pannel);

    var mainPage = document.getElementById('page');
    if(mainPage==null)return;

    mainPage.appendChild(pannel);
    //document.body.appendChild(pannel);


    YAHOO.util.Event.addListener(imgBtn,'click',fnc);
    
     
}

 
 function eco_theme_changed (theme) {


    var soustheme = document.getElementById('eco_sousTheme');

    for(var a=soustheme.options.length;a>-1;a--) {
        soustheme.options[a]=null;
    }

    var forumParent = theme.options[theme.selectedIndex].value;

    var item = new Array();

    for(var a=0;a<bb_forums.length;a++){

        if(bb_forums[a].forum_parent==forumParent){
            item.push(bb_forums[a]);
        }
    }

   soustheme.options[soustheme.options.length] = new  Option('','');

   for(a=0;a<item.length;a++) {
       soustheme.options[soustheme.options.length] = new  Option(item[a].forum_name  ,item[a].forum_id);
   }


 }

function newTopicValideform() {

    var err = false;
	document.getElementById('listTytleError').style.display='none';
	document.getElementById('listThemeError').style.display='none';
	document.getElementById('listSubThemeError').style.display='none';
	document.getElementById('listDiscussionError').style.display='none';
	document.getElementById('errTopicFrm').style.display='none';
     
	if(document.getElementById('eco_Titre' ).value.length==0){
		err=true;
		document.getElementById('listTytleError').style.display='block';
	}
	 
	if(document.getElementById('eco_theme' ).selectedIndex<=0){
		err=true;
		document.getElementById('listThemeError').style.display='block';
	}
	 
	if(document.getElementById('eco_sousTheme').selectedIndex<=0) {
         err=true;
		 document.getElementById('listSubThemeError').style.display='block';
     }

     if(document.getElementById('eco_texte' ).value.length==0){
		 err=true;
		 document.getElementById('listDiscussionError').style.display='block';
	 }
     
     if(err==true){
         var errPane = document.getElementById('errTopicFrm');
         errPane.style.display='block';
         return false;
     }

     var sousTheme = document.getElementById('eco_sousTheme');
     document.getElementById('forum_id').value=sousTheme.value;
     

     return true;

 }



 // related to EcoMobiliteExt plug


 function eco_voteAye(id,type,userId) {

    
    var cook = YAHOO.util.Cookie.get("ecoVote_"+id);

    if(cook=='vrai') return;

    var serviceEndPoint = acvu_blog_url + 'wp-content/plugins/EcoMobiliteExt/votesw.php?id='+id +'&type=' +type+'&user='+userId;

    var counter = document.getElementById('voteLoad_'+id);
    counter.style.display='inline';
    
     var callback =
	{
	  success: function(o){

            try {
               //alert(o.responseText);
               eval(o.responseText);
               var counter = document.getElementById('voteLoad_'+itemId);
               counter.style.display ='none';
               if(result==true){
                   var msg  = document.getElementById('voteText_'+itemId);
                   msg.innerHTML = message;
                   YAHOO.util.Cookie.set("ecoVote_"+itemId, "vrai", {expires: new Date("January 12, 2025")});
               }
             } catch(e) {

                alert(o.responseText);
             }
               

          }
              ,
	  failure: function(o) {

               // alert(o.responseText);
                }
            }

 YAHOO.util.Connect.asyncRequest('GET', serviceEndPoint, callback);


 }



var cb_bbProfil ={

      success: function (result) {
      //alert(result.responseText);
          var container = document.getElementById('results-relevant');

          var ajaxCounter = document.getElementById('bbAjaxCounter');
          ajaxCounter.style.display='none';
          container.style.height='auto';
          container.style.width='auto';
          container.innerHTML=result.responseText;
          YAHOO.util.Dom.setStyle(container,'opacity',1);
          bbLock=false;

          
      },
      /* Bbpress permalink bug, ca genere un 404 */
      failure:function(result){
       var container = document.getElementById('results-relevant');

          var ajaxCounter = document.getElementById('bbAjaxCounter');
          ajaxCounter.style.display='none';
          container.style.height='auto';
          container.style.width='auto';
          container.innerHTML=result.responseText;
          YAHOO.util.Dom.setStyle(container,'opacity',1);
          bbLock=false;
          //alert('failure :' +o.responseText);

          //alert(o.status);
      }

    };


var cb_wpProfil ={

      success: function (result) {
      //alert(result.responseText);
          var container = document.getElementById('boxmiddle');
          var ajaxCounter = document.getElementById('wpAjaxCounter');
          container.style.height='auto';
          ajaxCounter.style.display='none';
          container.innerHTML=result.responseText;
          YAHOO.util.Dom.setStyle(container,'opacity',1);
          wpLock=false;
          if(bbLock==true)
              showAndAlignAjaxCounter('bbAjaxCounter','results-relevant');


      },
      /* Bbpress permalink bug, ca genere un 404 */
      failure:function(result){

			// changed by Ivaylo: The next line was commented
          //alert('falure'+result.status);
      }

    };

var wpLock=false;
var bbLock=false;

function showAndAlignAjaxCounter(cntId,parentId){

    var ajaxCounter = document.getElementById(cntId);
    var container = document.getElementById(parentId);
    var contPos =  YAHOO.util.Dom.getXY(container);

    
    YAHOO.util.Dom.setStyle(container,'opacity',0.5);
    
    //container.
    
    document.body.appendChild(ajaxCounter)
    ajaxCounter.style.position='absolute';
    ajaxCounter.style.display ='block';

    ajaxCounter.style.top= ( contPos[1]+ container.offsetHeight/2 - (ajaxCounter.offsetHeight/2)  )  +'px';
    ajaxCounter.style.left = ( contPos[0]+ container.offsetWidth/2 - (ajaxCounter.offsetWidth/2)  )  +'px';


  

}



function bbNav(encodedUrl){

    if(bbLock==true) return;
    bbLock=true;
    showAndAlignAjaxCounter('bbAjaxCounter','results-relevant');
    var url = Base64.decode(encodedUrl);
   
    YAHOO.util.Connect.asyncRequest('GET', url, cb_bbProfil);



}

 function eco_MainProfil() {

    //alert(bbProfil);
    YAHOO.util.Connect.asyncRequest('GET', wpProfil, cb_wpProfil);
    YAHOO.util.Connect.asyncRequest('GET', bbProfil, cb_bbProfil);
    showAndAlignAjaxCounter('wpAjaxCounter','boxmiddle');
    showAndAlignAjaxCounter('bbAjaxCounter','results-relevant');
    //alert(wpProfil);

 }

function eco_MainSearch() {

     var search = wpProfil +'?s='+searchTerm/*+'&cat='+searchCat*/;
     //alert(search);
     YAHOO.util.Connect.asyncRequest('GET', search, cb_wpProfil);
     showAndAlignAjaxCounter('wpAjaxCounter','boxmiddle');
   //  showAndAlignAjaxCounter('bbAjaxCounter','results-relevant');
   //  var bbUrl = bbProfil + '?q=' + searchTerm;
    // alert(bbUrl);
    // YAHOO.util.Connect.asyncRequest('GET', bbUrl, cb_bbProfil);
    //search.php?q=
}

function wpNav(encodedUrl) {

    if(wpLock==true) return;
    wpLock=true;

    showAndAlignAjaxCounter('wpAjaxCounter','boxmiddle');
    var url = Base64.decode(encodedUrl);
    //alert(url);
    YAHOO.util.Connect.asyncRequest('GET', url, cb_wpProfil);

}


 /**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}


function eco_validePostSubmit() {
  
    var content = document.getElementById('post_content');
    var embed = document.getElementById('post_embed');

    if(content.value.length==0) {
        if(embed.value.indexOf('<embed')!=-1){
            content.value='#embed#';
        }
    }

    return true;

}




function eco_AdminUserProfil() {

    

      var stripper = function (element){

        var node= element.parentNode;
        while(node!=null) {
            if(node.nodeName=='TR')
                break;
            node = node.parentNode;
        }

        var tbody = node.parentNode;
        tbody.removeChild(node);
    }

    var help= document.getElementById('contextual-help-link-wrap');

    if(help!=null) {
        var p = help.parentNode;
        p.removeChild(help);
    }
    var form = document.getElementById('your-profile');
    if(form==null)return;

    var elementToRemove = new Array('aim','yim','jabber');

    for(a=0;a<elementToRemove.length;a++){

        var ele = document.getElementById(elementToRemove[a]);
        if(ele!=null){
            stripper(ele);
        }
    }



    
}

/* Functions that swaps layers. */
function montre(id) {
    if (document.getElementById) {
        document.getElementById(id).style.display = "block";
    } else {
        if (document.all) {
            document.all[id].style.display = "block";
        } else {
            if (document.layers) {
                document.layers[id].display = "block";
            }
        }
    }
}
function cache(id) {
    if (document.getElementById) {
        document.getElementById(id).style.display = "none";
    } else {
        if (document.all) {
            document.all[id].style.display = "none";
        } else {
            if (document.layers) {
                document.layers[id].display = "none";
            }
        }
    }
}

/* Functions that swaps images. */
function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments;
    document.MM_sr = new Array;
    for (i = 0; i < (a.length - 2); i += 3) {
        if ((x = MM_findObj(a[i])) != null) {
            document.MM_sr[j++] = x;
            if (!x.oSrc) {
                x.oSrc = x.src;
            }
            x.src = a[i + 2];
        }
    }
}
function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr;
    for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) {
        x.src = x.oSrc;
    }
}

function MM_findObj(n, d) { //v4.01
    var p, i, x;
    if (!d) {
        d = document;
    }
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) {
        x = d.all[n];
    }
    for (i = 0; !x && i < d.forms.length; i++) {
        x = d.forms[i][n];
    }
    for (i = 0; !x && d.layers && i < d.layers.length; i++) {
        x = MM_findObj(n, d.layers[i].document);
    }
    if (!x && d.getElementById) {
        x = d.getElementById(n);
    }
    return x;
}


var eco;
eco = {};
eco.form = {};



eco.form.starIdFocus = function (obj) {

    var value = obj.value;

    if(isNaN(value)) obj.value='';
}

eco.form.videoStarUpdFrm =function (name) {

    var frm = document.getElementById(name);

    //alert( document.forms.videoStarUpdFrm_0 );

}


///videoStarUpdFrm_<?php print $cnt; ?>.submit()

eco.form.actionDelete=function(id,form,action){

    if(!confirm ("Effacer l'item ?")) return false;

    var actionInput = document.getElementById('action_'+id);
    actionInput.value=action;
    eval('var frm = document.forms.'+form+id);
    frm.submit();




}


function ecoAgendaDelete(id) {

    var frm = document.getElementById('frm_'+id);
    var action = document.getElementById('action_'+id);

    if(!confirm ("Effacer l'item ?")) return false;

    action.value='delete';
    frm.submit();

}



 function acvu_ecoThemeChange() {

    var theme = document.getElementById('acvu_theme');
    var soustheme = document.getElementById('acvu_soustheme');
	if(!soustheme) return;
    for(var a=soustheme.options.length;a>-1;a--) {
        soustheme.options[a]=null;
    }

    var catParent = theme.options[theme.selectedIndex].value;

    var item = new Array();

    for(var a=0;a<acvu_cat.length;a++){
        if(acvu_cat[a].parent==catParent){
            item.push(acvu_cat[a]);
        }
    }

    soustheme.options[soustheme.options.length] = new  Option('','');

    for(a=0;a<item.length;a++) {
        soustheme.options[soustheme.options.length] = new  Option(item[a].name  ,item[a].id);
    }

}

// REDEFINITION

function startCallback(params) {

    var arErr = new Array();

 //   var soustheme = document.getElementById('acvu_soustheme' );
    var theme = document.getElementById('acvu_theme' );

    if(document.getElementById('acvu_titre').value.length==0)  arErr.push('Le titre.');
    //if(document.getElementById('acvu_soustheme' ).selectedIndex<=0) arErr.push('Le sous-théme.');


    if(theme.selectedIndex<=0) {
        arErr.push('Le thème.');
    } else {
        if( isNaN(theme.options[theme.selectedIndex].value ))
            arErr.push('Le thème.');
    }

/*
    if(soustheme.selectedIndex<=0) {
        arErr.push('Le sous-thème.');
    } else {
        if( isNaN(soustheme.options[soustheme.selectedIndex].value ))
            arErr.push('Le sous-thème.');
    }

*/


    if(document.getElementById('desc' ).value.length==0) arErr.push('Le synopsis.');
    if(document.getElementById('uploadName' ).value.length==0) arErr.push('Le fichier.');


    if(arErr.length!=0){
         document.getElementById('acvu_progress').style.display ='none';
         //document.getElementById('uploadForm').style.display = 'none';
         document.getElementById('validationFailled').style.display = 'inline';

         var errListDiv = document.getElementById('validationList');

         while(errListDiv.firstChild !=null)
             errListDiv.removeChild(errListDiv.firstChild);

         var list = document.createElement('UL');

         for(var item in arErr){
             var listItem = document.createElement('LI');
             listItem.appendChild( document.createTextNode(arErr[item] ));
             list.appendChild(listItem);
         }

         errListDiv.appendChild(list);
         AIM.cancelled=true;
         return false;
    }

    // upload approuvé.

    var pannel =  document.getElementById(params.id+'_pannel');
    pannel.lock=true;


    document.getElementById('validationFailled').style.display = 'none';
    var progress =document.getElementById('acvu_progress');
    progress.style.display  = 'block';

    var overlay = document.getElementById('acvu_overlay');
    YAHOO.util.Dom.setStyle(overlay, 'opacity', 0.0);
    overlay.style.display = 'inline';
    //overlay.style.background ='#808080';
    //YAHOO.util.Dom.setStyle(overlay, 'opacity', 0.5);

    return true;
}


function clearForm(id) {
    try {
        document.getElementById('validationFailled').style.display ='none';
        document.getElementById('uploadName' ).value ='';
        document.getElementById('uploadName' ).defaultValue='';
        document.getElementById('acvu_titre' ).value='';
        document.getElementById('desc'  ).value='';
        document.getElementById('acvu_theme' ).selectedIndex=0;
        document.getElementById('acvu_soustheme' ).selectedIndex=0;
    } catch(e){
       // alert(e);
    }
}


var actuState=false;
function showHideActu(){

     
    var ele = document.getElementById('actuWin');
    var sideContainer = document.getElementById('boxactu');


   
    
    if(actuState==true){
        ele.style.display='none';
        actuState=false;
    } else {
        ele.style.display='block';
        ele.style.left = (70) + 'px';

        ele.style.top = (-20)+'px';

        //ele.style.top = ((sideContainer.offsetTop+sideContainer.offsetHeight)- ele.offsetHeight)  +'px';
//        var cntPos = YAHOO.util.Dom.getXY(sideContainer);
//        ele.style.position ='absolute';
//        var left = cntPos[0] - ele.offsetWidth;
//        var top  = cntPos[0] - ele.offsetHeight +0 ;
//        ele.style.left = left+'px';
//        ele.style.top = top +'px';

        actuState=true;
    }
}
function check_term(){
	var termBox = document.getElementById('s');
	if (jQuery.trim(termBox.value) == ''){
		return false;
	}
    return true;
}
