//<![CDATA[
/*
 Copyright (c) 2007 Caridy Patiño. All rights reserved.
 version 0.1.0
 Author: Caridy Patiño (caridy at gmail.com)
*/
YAHOO.namespace("App");
(function() {

  var $B = YAHOO.Bubbling,
  	  $L = YAHOO.util.Lang,
	  $E = YAHOO.util.Event,
	  $D = YAHOO.util.Dom,
	  $ =  YAHOO.util.Dom.get;

  /**
    * Este metodo hace un parsing de una url, completa sus parametros sobrescribiendo parametros que se pasan como m a la funcion
    * @public
    * @param {string} url URI de navegaciï¿½n
    * @param {string} m   MoreParams representa una cadena de parametros con el siguiente formato ( param1=value1&param2=value2 )
    * @return string
    */
    function url_completion ( url, m ) {
      var anch = '';
      var p    = '';
      var params = '';
      var moreparams = new String(m);
      var query = new Array();
      // separando la url en sus 3 partes (url, parametros, anchor)
      if (url.indexOf('#') > -1) {
    	 anch = url.substring ( url.indexOf('#'), url.length );
    	 url  = url.substring ( 0, url.indexOf('#') );
      }
      if (url.indexOf('?') > -1) {
    	 params = url.substring ( url.indexOf('?')+1, url.length );
    	 url   = url.substring ( 0, url.indexOf('?') );
      }
      // sustituyendo el separados de parametros para que no de problema con ajax
      while (params.indexOf ( '&amp;' ) > -1)
        params = params.replace ( '&amp;', '&' );
      while (moreparams.indexOf ( '&amp;' ) > -1)
        moreparams = query.replace ( '&amp;', '&' );

      // este bloque verifica que no se repitan los parametro en la url de resultado
      // tener en cuenta que los moraparams tienen prioridad sobre los parametros que ya venian en la url
      query = query.concat ( params.split ('&'), moreparams.split ('&') );
      var tmp = new String('');
      var par = new Array ();
      var s   = new String();
      query = query.reverse();
      for (var i=0; i<query.length; i++) {
    	s = new String (query[i]);
    	par = s.split ('='); // array( param, value )
    	if (tmp.indexOf ('{'+par[0]+'}') > -1)
    	  query[i] = null;
    	else
          tmp += '{'+par[0]+'}';
      }
      // una vez eliminados los parametros que estaban repetidos se procede a construir la url.
      for (var i=0; i<query.length; i++) {
        if (query[i] != null)
    	  if (p == '') p += '?'+query[i]; else p += '&'+query[i];
      }
      return url + p + anch;
    }

	YAHOO.App.Core = function () {
	    var obj = {};
		try {
			obj.flags = DEFAULT_VARS;
		} catch(e) {
			obj.flags = {};
		}
        // Private Methods
		var actions = {
			navRecommendPage: function (layer, args) {
				  var el = args[1].anchor,
				      r = document.location+'';
				  if (el) {
				    var page  = base64encode(utf16to8(r)),
				    	title = document.title;
				    document.location = YAHOO.CMS.Common.url_completion ( el.href, '_title=' + title  + '&_url=' + page );
				    return true;
				  }
			},
			actionFormFieldFocus: function (layer, args) {
				  var el = $B.getAncestorByTagName( args[1].target, 'A' );
				  if (el && el.id && (el.id.indexOf('setfocus') === 0)) {
				  	// calculating the form field ID
				  	var field = $(el.id.slice (8, el.id.length));
					if (field) {
					  field.focus();
					}
				  }
			},
			actionDisplayVideo: function (layer, args) {
				if (!args[1].decrepitate && args[1].button && args[1].button.get('value')) {
				    var dialog = new YAHOO.widget.SimpleDialog("videodialog", {
				  	              width : "450px",
								  height : "400px",
								  fixedcenter : true,
								  visible : false,
		                          modal : true,
								  constraintoviewport : true,
								  postmethod: 'none'
							   });
					// Render the Dialog
					dialog.render(document.body);
					dialog.setHeader('Video Player &nbsp; ');
					dialog.setFooter('');
			        dialog.setBody(args[1].button.get('value'));
			        dialog.show();
			        $E.stopEvent(args[0]);
				    args[1].decrepitate = true;
				}
			},
			actionAjaxGallery: function (layer, args) {
				if (!args[1].decrepitate && args[1].button && args[1].button.get('value')) {
					var content = document.createElement("span");
					content.innerHTML = "&nbsp;";
					var success = function(o){
						if((o.responseText != 'undefined') && (o.argument.c)){
						  YAHOO.CMS.Common.displayDialog( o.argument.c, o.responseText, '50em', true );
						  var myGallery = new YAHOO.widget.Gallery('gallery', { container:'yuigallery' } );
						}
					};
					var failure = function(o){};
				    YAHOO.CMS.Common.ajaxLoadContent ( content,  url_completion ( args[1].button.get('value'), 'tpl=tpls/ajax&ajax=true&page=pages/object-gallery' ), success, failure);
				}
			}
		};
		$B.on('navigate', function (layer, args) {
		  $B.processingAction (layer, args, actions);
	    });

		var actionAdjustImages = function (layer, args) {
		  adjust_images_by_id ( 'big-imgs', 480 );
	    };
		window.actionAdjustImages = actionAdjustImages;
        // Public Vars
		obj.navHistory = [];
    	obj.DataSources = {};
        // Public Methods
		obj.init = function () {
		  // ajuste de las imagenes en el cuerpo de la página...
		  actionAdjustImages();
		  //$B.bubble.repaint.subscribe(actionAdjustImages);

		  this.loadDots ();
		  this.navHistory.push ( window.location.href );
		};
		obj.initCategories = function () {
		    YAHOO.CMS.behaviors.Categories.load ({uri:'/kernel/json/categories.php?lang='+TMS_CURRENT_LANG+'&cat_id=0&depth=2'});
		};
		obj.initSelector = function () {
		};
		obj.initHints = function () {
            YAHOO.widget.TooltipManager.init();
            YAHOO.widget.TooltipManager.config ({
                width: '250px'
            });
		};
		obj.initLocutor = function () {
		  // creating the info panel...
		  YAHOO.CMS.Common.values.hold( new YAHOO.CMS.widget.InfoPanel( 'locutor',
										 {
										   handle:'locutorhandle',
										   context:'ajax-locutor-content',
										   webpart:'webparts/ajax/advice.inc.html',
										   force:false
										 }
										)
									  );
		};
		obj.initPanels = function () {
		};
		obj.loadDots = function () {
		  // preloading common dots
		  with ({p:TMS_THEMEPATH, m: YAHOO.CMS.Common.preloadImages}) {
			  m(p + '/images/dot.jpg', p + '/images/dot1.jpg', p + '/images/dot2.jpg', p + '/images/dot3.jpg', p + '/images/dot4.jpg', p + '/images/dot5.jpg', p + '/images/dot6.jpg');
			  m(p + '/images/loading.gif');
		  }
		};
		obj.initMenuBar = function () {
		  var oMenuBar = new YAHOO.widget.MenuBar('quickaccess', { autosubmenudisplay: true, hidedelay: 750, lazyload: true });
          oMenuBar.render();
		};
		// collecting a list of buttons...
		// and hacking the new button creation keeping the classname already defined for each element...
		obj.buttons = function (items) {
		    $E.onDOMReady(function(){
            	var i, el;
            	items = ($L.isArray(items)?items:[items]);
            	for (i=0; i < items.length; i++) {
                  el = ($L.isObject(items[i])?items[i]:$(items[i]));
    		      if (el) {
    		        new YAHOO.widget.Button(el, {className: el.className});
    		      }
            	}
            });
		};
		obj.closing = function (items) {
		  obj.initSelector();
		  obj.initHints();
		  if (items.length > 0) {
		    for(k = 0; k < items.length; k++) {
		        YAHOO.plugin.Dispatcher.jsLoader ( items[k].file, {after: items[k].method} );
		    }
		  }
		};
  	    return obj;
	}();
	// Initialize and render dynamic elements using onContentReady event for each webpart
	$E.onDOMReady(YAHOO.App.Core.init, YAHOO.App.Core, true);
	$E.onContentReady('quickaccess', YAHOO.App.Core.initMenuBar, YAHOO.App.Core, true);
})();

function adjust_images_by_id ( el, maxwidth ) {
  if ((typeof el == 'object') || (el = document.getElementById( el ))) {
    var objs = el.getElementsByTagName( 'img' );
    adjust_images ( objs, maxwidth );
  }
}
function adjust_images_by_name ( tagname, maxwidth ) {
  var obj_containers = getElementsByClassName(document, tagname);
  var objs = new Array();
  for(var i = 0; i < obj_containers.length; i++) {
	var images = obj_containers[i].getElementsByTagName( 'img' );
	objs = objs.concat(images);
  }
  adjust_images ( objs, maxwidth );
}
function adjust_images ( images, maxwidth ) {
  var w = 0;
  var h = 0;
  var ratio = 1;  
  for(var i = 0; i < images.length; i++) {
     w = parseInt(images[i].width);
     if (!(w > 0)) w = parseInt(images[i].style.width);
     if (w > maxwidth) {	   
       h = parseInt(images[i].height);
       if (!(h > 0)) h = parseInt(images[i].style.height);
       images[i].style.width = maxwidth+'px';
       images[i].width       = maxwidth;
       if (h > 0) {
         images[i].style.height = (h * maxwidth / w)+'px';
         images[i].height 	    = h * maxwidth / w;
       }
     }
  }
  return true;
}
// menus dinamicos...
function init_states_list( obj_id ) {
   var obj = YAHOO.util.Dom.get ( obj_id );
   if (obj && obj.options) {
     reset_list ( obj ); // eliminando todos los elementos...
     var items = estados['states'];
	 insert_into_list (obj, '', '');
     for(var n=0; n < items.length; n++)
	   insert_into_list (obj, items[n].s, items[n].s);
	 return true;
   }
   else
     return false;
}
function init_cities_list( obj_id, state_id ) {
   var obj = YAHOO.util.Dom.get ( obj_id );
   var sta = YAHOO.util.Dom.get ( state_id );
   var indx = prepare_indx ( sta.value );
   if (sta && sta.options && sta.value && obj && obj.options && (ciudades[indx])) {
     reset_list ( obj ); // eliminando todos los elementos...
     var items = ciudades[indx];
	 insert_into_list (obj, '', '');
     for(var n=0; n < items.length; n++)
	   insert_into_list (obj, items[n].c, items[n].c);
	 return true;
   }
   else
     return false;
}
function init_marks_list( obj_id ) {
   var obj = YAHOO.util.Dom.get ( obj_id );
   if (obj && obj.options) {
     reset_list ( obj ); // eliminando todos los elementos...
     var items = marcas['marks'];
	 insert_into_list (obj, '', '');
     for(var n=0; n < items.length; n++)
	   insert_into_list (obj, items[n].m, items[n].m);
	 return true;
   }
   else
     return false;
}
function init_models_list( obj_id, mark_id ) {
   var obj = YAHOO.util.Dom.get ( obj_id );
   var mar = YAHOO.util.Dom.get ( mark_id );
   var indx = prepare_indx ( mar.value );
   if (mar && mar.options && mar.value && obj && obj.options && (modelos[indx])) {
     reset_list ( obj ); // eliminando todos los elementos...
     var items = modelos[indx];
	 insert_into_list (obj, '', '');
     for(var n=0; n < items.length; n++)
	   insert_into_list (obj, items[n].m, items[n].m);
	 return true;
   }
   else
     return false;
}
function prepare_indx ( i ) {
   var indx = new String ( i );
   while (indx.indexOf ( '/' ) > -1)
     indx = indx.replace ( '/', ' ' );
   while (indx.indexOf ( ' ' ) > -1)
     indx = indx.replace ( ' ', '_' );
   return indx;
}
function reset_list ( obj ) {
   while (obj.options.length > 0) { // eliminando todos los elementos...
	if ( navigator.appName == 'Netscape' )
	  obj.options[0] = null;
	else  
	  obj.options.remove (0);
   }
}
function auto_selection ( id, value ) {
  var id_obj = YAHOO.util.Dom.get ( id );
  if (id_obj)
	for (var i = 0; i < id_obj.length; i++)
	  if (id_obj.options[i].value == value)
		id_obj.options[i].selected = true;
  return true;
}
//]]>