// Sergi Meseguer http://www.zigotica.com/ 
// Joaquín Martí http://www.joaquinmarti.com/

var DMSTK = {
    
/*::::::::::::::::::::::::::::::::: CUFON :::::::::::::::::::::::::::::::::*/		
      initCufon : function() {
          $('*.CR').each(function() {                
              var selector = '#' + $(this).parents('*[id]').eq(0).attr('id') + ' ' + this.tagName+(($(this).attr('id'))? '#'+$(this).attr('id') : '')+(($(this).attr('class'))? '.'+$(this).attr('class').replace(/ /g, '.') : '');
              var options = {
                  fontFamily: ($(this).css('font-family') != null ? $(this).css('font-family') : "Hermes") /* Fix Opera bug */
              };
              if ($(this).hasClass('text_shadow')) {
                 options.textShadow = '#111111 1px 1px';
              }
              if ($(this).hasClass('hover')) {
                 options.hover = true;
              }
              Cufon.replace (selector, options);
          });
      },

/*::::::::::::::::::::::::::: DATES AGO ::::::::::::::::::::::::::::::*/

      /*
      * Javascript Humane Dates - spanish translation
      * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
      * Re-write by Zach Leatherman (zachleat.com)
      * 
      * Adopted from the John Resig's pretty.js
      * at http://ejohn.org/blog/javascript-pretty-date
      * and henrah's proposed modification 
      * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
      * 
      * Licensed under the MIT license.
      */
      humane_date : function(date_str, now_str){
      	var time_formats = [
      		[60, 'ahora mismo'],
      		[90, '1 minuto'], // 60*1.5
      		[3600, 'minutos', 60], // 60*60, 60
      		[5400, '1 hora'], // 60*60*1.5
      		[86400, 'horas', 3600], // 60*60*24, 60*60
      		[129600, '1 día'], // 60*60*24*1.5
      		[604800, 'días', 86400], // 60*60*24*7, 60*60*24
      		[907200, '1 semana'], // 60*60*24*7*1.5
      		[2628000, 'semanas', 604800], // 60*60*24*(365/12), 60*60*24*7
      		[3942000, '1 mes'], // 60*60*24*(365/12)*1.5
      		[31536000, 'meses', 2628000], // 60*60*24*365, 60*60*24*(365/12)
      		[47304000, '1 año'], // 60*60*24*365*1.5
      		[3153600000, 'años', 31536000], // 60*60*24*365*100, 60*60*24*365
      		[4730400000, '1 siglo'] // 60*60*24*365*100*1.5
      	];

      	var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," ");
        var now = now_str.replace(/-/g,"/").replace(/[TZ]/g," ");
        var seconds = (new Date(now) - new Date(time)) / 1000;
    		var token = 'hace ';
      	var	i = 0;

      	if (seconds < 0) {
      		seconds = Math.abs(seconds);
      		token = '';
      	}

      	while (format = time_formats[i++]) {
      		if (seconds < format[0]) {
      			if (format.length == 2) {
      				return (i > 1 ? token : '') + format[1]; // Conditional so we don't return Just Now Ago
      			} else {
      				return token + Math.round(seconds / format[2]) + ' ' + format[1];
      			}
      		}
      	}

      	// overflow for centuries
      	if(seconds > 4730400000){
      		return Math.round(seconds / 4730400000) + ' siglos' + token;
        }
      	return date_str;
      },

    formatTimestamp : function(timestamp){
      
    },

    datesAgo : function(now_str){
      $('.time_ago').map( function(){
          timestamp = $(this).find('.timestamp').text();
          pretty = DMSTK.humane_date(timestamp, now_str);
          $(this).text(pretty);
        }
      );
    },


/*::::::::::::::::::::::::::::::::: ROUNDED CORNERS :::::::::::::::::::::::::::::::::*/
		roundeMeNow : function() {
			$(".to_hell_with_rounded_corners, .content_module, #portfolio_project_preview_page #main_content").each(function(i){
			   $(this).append('<span class="rc ne"></span><span class="rc nw"></span><span class="rc se"></span><span class="rc sw"></span>');
			});
		},
		
/*::::::::::::::::::::::::::::::::: TARGET POPUPS :::::::::::::::::::::::::::::::::*/
		autoPopup : function() {
			$(".popup").each(function(i){
				$(this).attr("target", "_blank");
			});
		},
		
/*::::::::::::::::::::::::::::::::: DOCK :::::::::::::::::::::::::::::::::*/
		DOCKED : 0,
		
		createDock : function(){
			if(!$("#forums_publish_response_title")) return;
			var cont = '<ul class="common_actions" id="dock_button_container"><li><a href="javascript:DMSTK.toggleDock();" id="common_actions_complete_list" class="FR arrow_right"><span>Dock</span></a></li></ul>';
			$("#forums_publish_response_title").before(cont); 
		},
		
		toggleDock : function(){
			if(DMSTK.DOCKED == 0){ 
				$("#dock_button_container").parent().parent().addClass("docked");
				DMSTK.DOCKED = 1;
			}
			else {
				$("#dock_button_container").parent().parent().removeClass("docked");
				DMSTK.DOCKED = 0;
			}
		},		

/*::::::::::::::::::::::::::::::::: QUOTE ME :::::::::::::::::::::::::::::::::*/
		prepareQuotes : function(){
			if(window.DMSTK_LOGGED == undefined) return; 
				DMSTK.BASEURL = location.href; 
				$(".meta[title] ul").each(function(i){
					var TITLE = $(this).parents('.meta').attr("title");
					var ID = TITLE.split("||")[1];
					var USER = TITLE.split("||")[0];
					$(this).append('<li class="quoteme"><a href="#" onclick="DMSTK.quoteMe(\''+ID+'\', \''+USER+'\');return false;" class="IR"><span>Citar</span></a></li>');
				}); 
		}, 
		
		quoteMe : function(ID, USER){
			var metaElm = $("#response_" + ID).siblings(".meta");
			var url = "/mensajes/"+ID+"/bbcode";
			$(metaElm).append('<span class="citando_mensajes"> (...citando)</span>');
			
		 		 	$.ajax({
				 		type: "get",
				 		url: url,	
						data: null,
						dataType: "html",						

						error: function(data, msg, err){
							var TXT = $("#response_" + ID).html();
							$("#message_body").val($("#message_body").val() + "[quote="+USER+"]"+TXT+"[/quote]");
				 		},
											
					 	success: function(data){
							$("#message_body").val($("#message_body").val() + "[quote="+USER+"]"+data+"[/quote]");
				 		},
						
						complete : function() {
							$(".citando_mensajes").fadeOut(500).end().remove();
							setTimeout("DMSTK.takeMeThere()",500);
						}
				 	});
								
		},
			
		takeMeThere : function(){
			location.href = DMSTK.BASEURL + "#forums_publish_response";
			$("#message_body").focus();
		},
		
		
/*::::::::::::::::::::::::::::::::: UN/MARK INPUTS :::::::::::::::::::::::::::::::::*/
		prepareMarkInputsLink : function(){
			if(!$("#message_order_title")) return;
			var cont = '<a href="javascript:DMSTK.toggleInputs(\'form_listado_mensajes\');">All/None</a>';
			$("#message_order_title").after(cont); 
		},

		toggleInputs : function(fm){
			var target = document.getElementById(fm);
			var inputs = target.getElementsByTagName("input");
			for (var i = 0; (input = inputs[i]); i++) {
				if(input.type == "checkbox" && input.checked == true) input.checked = false;
				else if(input.type == "checkbox" && input.checked == false) input.checked = true;
			}
		},
	
/*::::::::::::::::::::::::::::::::: STICKY FINGERS... OR FORMS :::::::::::::::::::::::::::::::::*/
		stickMyForms : function(){
			$(".stickme").each(function(i){
				var myF = this;
				$(this.elements).each(function(j){
					$(this).bind("focus", function(e){
					      $(myF).addClass("sticky");
				    });				
					$(this).bind("blur", function(e){
					      $(myF).removeClass("sticky");
				    });		
				});
		    });
		},
		
/*::::::::::::::::::::::::::::::::: TAKE CARE OF EMAIL IN QUICK LOGIN :::::::::::::::::::::::::::::::::*/
		labelifyEmail : function(){
			$("#quickemail").bind("focus", function(e){
			      if($("#quickemail").val() == "email") $("#quickemail").val("");
		    });				
			$("#quickemail").bind("blur", function(e){
			      if($("#quickemail").val() == "") $("#quickemail").val("email");
		    });	
		},
		
/*::::::::::::::::::::::::::::::::: CONTROLLING PAGINATOR DIV :::::::::::::::::::::::::::::::::*/

		PAGINATOR_READY : false,

		preparePaginator : function() {
			if(!$('.paginator').length) return;
			if($('.paginator.static').length) return;
			/*
			if ($('ul#forum_responses').length) {
				$('div.paginator').css('top', $('ul#forum_responses').position().top).css('margin-top', '0em');	
			}
			*/
			paginatorOffsetOriginalTop = $('.paginator').offset().top;
			paginatorPositionOriginalTop = $('.paginator').position().top;
			paginatorHeight = $('.paginator').height();
			paginatorMarginBottom = parseInt($('.paginator').css('margin-bottom').substring(0, $('.paginator').css('margin-bottom').length-2));
			
			mainContentTop = $('#main_content').position().top;
			mainContentHeight = $('#main_content').height();
			
			parentContentTop = $('.paginator').offsetParent().position().top;
			parentContentHeight = $('.paginator').offsetParent().height();
			parentPaddingBottom = parseInt($('.paginator').offsetParent().css('padding-bottom').substring(0, $('.paginator').offsetParent().css('padding-bottom').length-2));
			parentPaddingTop = parseInt($('.paginator').offsetParent().css('padding-top').substring(0, $('.paginator').offsetParent().css('padding-top').length-2));
			
			DMSTK.PAGINATOR_READY = true;
			DMSTK.movePaginator();
			
		},
		
	
		movePaginator : function() {
			if(!$('.paginator').length) return;
			if($('.paginator.static').length) return;
			
			if (DMSTK.PAGINATOR_READY) {
			
				startScroll = paginatorOffsetOriginalTop - paginatorPositionOriginalTop;
				stopScroll = mainContentTop + mainContentHeight - paginatorHeight - paginatorPositionOriginalTop - paginatorMarginBottom;
				
				maxPaginatorPosition = parentContentHeight + parentPaddingBottom + parentPaddingTop - paginatorHeight - paginatorMarginBottom;				
					
				
				// Limits			
				if (startScroll < $(window).scrollTop() && $(window).scrollTop() < stopScroll) {		
					$('.paginator').css('position', 'fixed');
					$('.paginator').css('top', paginatorPositionOriginalTop);
					if(($.browser.msie && parseInt($.browser.version) == 7)) 
						$('.paginator').css('margin-left', '-22.3em');
				}
				else {					
					$('.paginator').css('position', 'absolute');
					
					if (startScroll > $(window).scrollTop()) $('.paginator').css('top', paginatorPositionOriginalTop);
					if ($(window).scrollTop() > stopScroll) $('.paginator').css('top', maxPaginatorPosition);
					
					$('.paginator').css('margin-left', '-4.4em');
				}
				
			}

		},
												 
/*::::::::::::::::::::::::::::::::: CONFIRMATION WINDOW :::::::::::::::::::::::::::::::::*/

		prepareConfirmationFieldset : function() {
			if(!$('fieldset.confirmation_fieldset').length) return;
			$('fieldset.confirmation_fieldset').css('display', 'none');
			
			$('fieldset.confirmation_fieldset div.form_field').append('<a href="#" class="confirmation_accept button">Aceptar</a>');
			$('fieldset.confirmation_fieldset div.form_field').append('<a href="#" class="confirmation_cancel button">Cancelar</a>');
			
			$('#form_profile_administration').prepend('<div id="confirmation_background" style="display: none"></div>');
			$('fieldset.confirmation_fieldset').clone(true).prependTo('#form_profile_administration');
			$('fieldset.confirmation_fieldset').eq(1).remove();
			
			$('div.submit_field button').click(function() {
				DMSTK.showWindow();
				return false;
			});
		},
		
		showWindow : function () {

			$(document.body).addClass("applications_active");
			$('#confirmation_background').css('display', 'block');
			$('fieldset.confirmation_fieldset').fadeIn('slow');
			$('fieldset.confirmation_fieldset').addClass('box');
			$('input#password').focus();
			
			$('#confirmation_background').click(function() {
				$('.confirmation_cancel').trigger('click');	
			});
			
			$('.confirmation_cancel').click(function() {
				$(document.body).removeClass("applications_active");
				$('#confirmation_background').css('display', 'none');
				$('fieldset.confirmation_fieldset').css('display', 'none');
				$('fieldset.confirmation_fieldset').removeClass('box');
				
				return false;
			});
			
			$('.confirmation_accept').click(function() {
				$('.confirmation_cancel').trigger('click');
				$('form#form_profile_administration').submit();
				return false;
			});
			return false;
		},
		
/*::::::::::::::::::::::::::::::::: INPUT TYPE SUBMIT TO BUTTON :::::::::::::::::::::::::::::::::*/

		submitToButton : function() {
			$('input[type="submit"].to_button').each(function(i) {
				$(this).replaceWith('<button class="'+$(this).attr('class')+'" id="'+$(this).attr('id')+'" name="'+$(this).attr('name')+'" type="submit"><strong class="FR"><span>'+$(this).attr('value')+'</span></strong></button>');	
			});
		},
		
/*::::::::::::::::::::::::::::::::: STEPS MODULE :::::::::::::::::::::::::::::::::*/

        stepsModule : function() {
            if ($('div.steps_module').length == 0) return;
            
            /* Sizes */
            var liWidth = $('div.steps_module div.steps ol li').eq(0).width();
            $('div.steps_module').css('height', $('div.steps_module').css('min-height'));
            $('div.steps_module div.steps_content').css('display', 'none');
            $('div.steps_module div.steps ol').css('width', $('div.steps_module div.steps ol li').length * liWidth);
            $('div.steps_module h2').css('cursor', 'pointer');
            $('div.steps_module h2').css('position', 'absolute');
            $('div.steps_module div.call_to_action').css('display', 'none');
            
            /* Init steps */
            $('div.steps_module h2').click(function() {
                $(this).parents('*').eq(0).find('> h2, > p').css('display', 'none');
                $('div.steps_module div.steps_content').css('display', 'block');
                $('ol.table_of_content li:eq(0) a').addClass('active');
                $('div.steps_module div.call_to_action').css('display', 'block');
            
                /* Steps controls */
                $('div.steps_module').append('<ul class="steps_controls"><li class="previous"><a href="#" rel="prev" class="IR"><span>Anterior</span></a></li><li class="next"><a href="#" rel="next" class="IR"><span>Siguiente</span></a></li></ul>');
                
                $('ul.steps_controls li.previous a').click(function() {
                    var linkId = $('div.steps_module div.steps ol li.active').prev().attr('id');
                    if ($('li#'+linkId).length > 0) {
                        DMSTK.changeStep(linkId);
                    }
                    return false;
                });

                $('ul.steps_controls li.next a').click(function() {
                    var linkId = $('div.steps_module div.steps ol li.active').next().attr('id');
                    if ($('li#'+linkId).length > 0) {
                        DMSTK.changeStep(linkId);
                    }             
                    return false;
                });
                
                /* Index controls */
                $('ol.table_of_content li a').each(function() {
                    $(this).click(function() {
                        var linkId = $(this).attr('href').substring( 1, $(this).attr('href').length);
                        DMSTK.changeStep(linkId);
                        return false;
                    });
                });
            
            });
            
        },
        
        changeStep : function(stepId) {
            var newActiveIndex = 0;
            var liWidth = $('div.steps_module div.steps ol li').eq(0).width();

            $('div.steps_module div.steps ol li.active').removeClass('active');
            $('li#'+stepId).addClass('active');
            $('ol.table_of_content li a').removeClass('active');
            $('ol.table_of_content li a[href=#'+stepId+']').addClass('active');
            
            newActiveIndex = parseInt($('div.steps ol li.active').attr('id').substring( $('div.steps ol li.active').attr('id').indexOf('_') + 1, $('div.steps ol li.active').attr('id').length ));
            
            $('div.steps_module div.steps ol').animate({
                left: ((newActiveIndex - 1) * liWidth * -1)
            }, 500);
      
        },


/*:::::::::::::::::::::::: GENERIC HIDDEN IFRAME UPLOAD ::::::::::::::::::::::*/
	/*
	Adds a hidden iframe after the form#source_form_id. 
	When the input[name=source_input_name] content changes:
	- a new form is generated inside the frame, the input file is copied and sent from the iframe
	- the div#result_id is replaced by a div.upload_wait
	- when the iframe receives the upload response, the inserted div.upload_wait is replaced by the response
	*/
	setupUploadIframe : function(source_form_id, source_input_name, result_id, method){

		escaped_input_name = source_input_name.replace('[','_').replace(']','_')
		frame_id = escaped_input_name + '_upload_iframe';
		frame_form_id = escaped_input_name + '_upload_form';

		// Content functions 
		if ($('form#'+source_form_id).length) {

			//Asynchronous upload
			DMSTK.loadUploadIframe(source_form_id, frame_id, result_id);
			DMSTK.addAsynchronousUploadByIframe(source_form_id, source_input_name, frame_id, frame_form_id, result_id, method);
		}		
	},

	loadUploadIframe : function(form_id, frame_id, result_id) {
	
		$('form#'+form_id).after('<iframe id="'+frame_id+'" name="'+frame_id+'"></iframe>');
		$('iframe#'+frame_id).css('display', 'none');

		$('iframe#'+frame_id).load(function() {
			response = $('iframe#'+frame_id).contents().find('body').html();
			
			if (response) {
				$('div#'+result_id).replaceWith(response);
			}
		});	
	},

	addAsynchronousUploadByIframe : function(form_id, input_name, frame_id, frame_form_id, result_id, method){
		$('input[name="'+input_name+'"]').bind('change', function(object) {

			// Create form
			hidden_method = '<fieldset><input type="hidden" name="_method" value="'+method+'" /></fieldset>';
			newForm = '<form action="'+$('form#'+form_id).attr('action')+'" target="'+frame_id+'" method="POST" enctype="multipart/form-data" accept-charset="'+$('form#'+form_id).attr('accept-charset')+'" id="'+frame_form_id+'">'+hidden_method+'<fieldset><input type="hidden" name="iframe" value="1" /></fieldset></form>';
			$('iframe#'+frame_id).after(newForm);
			
			// Create a new empty input file for the next upload
			newInput = '<input type="file" name="'+$(this).attr('name')+'" />';
			$(this).after(newInput);
			
			// Move the input file element, $(this) changes its position
			$('form#'+frame_form_id).append($(this));
			
			// Submit the form
			$('form#'+frame_form_id).submit();
			$("div#"+result_id).prepend('<div id="'+result_id+'_wait" class="uploading"><span>Uploading...</span></div>');
		
			// Remove form
			$('form#'+frame_form_id).remove();
		
			// Rebind the event for the new input file
			DMSTK.addAsynchronousUploadByIframe(form_id, input_name, frame_id, frame_form_id, result_id, method);
		});
	},

/*::::::::::::::::::::::::::::: PORTFOLIO COVER ::::::::::::::::::::::::::::::*/

		initPortfolioCoverForm : function(){
			DMSTK.setupUploadIframe('edit_portfolio_cover', 'portfolio_cover', 'portfolio_cover', 'PUT');
			$('#edit_portfolio_cover').addClass('jsok');
		},

/*::::::::::::::::::::::::::::::::: PORTFOLIOS FILTERS :::::::::::::::::::::::::::::::::*/

        filterPortfolios : function() {
          date = $('[name=date]').val();
          sort_by = $('[name=sort_by]:checked').val();
          area = $('[name=area]').val();
          //url = '/portfolios';
          url = $('div#portfolio_filter form').attr('action');
          url += '/' + sort_by;
          url += '/' + date;
          url += '/area/' + area;
          window.location = url;
          return false;
        },

        initFilters : function() {
            if ($('div#portfolio_filter').length == 0) return;
            $('div#portfolio_filter form fieldset.submit_field').css('display', 'none');
            $('div#portfolio_filter fieldset.filter_type input[type=radio]').css('display', 'none');
            
            $('div#portfolio_filter fieldset.filter_type label strong').each(function(i) {
                $(this).click(function() {
                    $('div#portfolio_filter fieldset.filter_type label').removeClass('selected');
                    $(this).parents('label').eq(0).addClass('selected');
                    $(this).parents('label').eq(0).find('input').attr('checked', 'checked');
                    DMSTK.filterPortfolios();
                });

            });
            
            // Marcar radio de filtro seleccionado
            $('#portfolio_filter input:checked').each(function(){
              $(this).parents('label').eq(0).addClass('selected');
            });            

            $('div#portfolio_filter fieldset.filter_date_and_area label select').each(function(i) {
                var new_select_id = $(this).attr('name');
                var new_select = '<div id="'+new_select_id+'"><ul></ul></div>';
                
                $(this).css('display', 'none');
                $(this).after(new_select);
                
                $(this).find('option').each(function(n) {
                    $('div#'+new_select_id).find('ul').append('<li id="'+new_select_id+'_'+$(this).attr('value')+'">'+$(this).html()+'</li>');
                });
                
                // Marcar li de option seleccionada
                var selected_option = $('[name="'+new_select_id+'"] option:selected');
                var selected_li_id = new_select_id + '_' + selected_option.val();
                $('#'+selected_li_id).addClass('selected');
                
                $('div#'+new_select_id).prepend('<strong>' + $('div#'+new_select_id).find('ul li.selected').html() + '</strong>');
                
                $('div#'+new_select_id).find('strong').click(function() {
                    if ($('div#'+new_select_id).hasClass('expanded')) {
                        $('div#'+new_select_id).removeClass('expanded');
                    }
                    else {
                        $('div#'+new_select_id).addClass('expanded');
                    }
                });
                
                $('div#'+new_select_id).find('ul li').each(function(m) {
                    $(this).click(function() {
                        var name = $(this).attr('id').substring(0, $(this).attr('id').indexOf('_'));
                        var value = $(this).attr('id').substring($(this).attr('id').indexOf('_') + 1, $(this).attr('id').length);
                        
                        $(this).parents('div').eq(0).find('strong').html($(this).html());
                        $(this).parents('div').eq(0).removeClass('expanded');
                        $(this).parents('label').eq(0).find('select[name='+name+']').find('option[value='+value+']').attr('selected', 'selected');

                        DMSTK.filterPortfolios();
                    });
                });
                
            });
            
        },

/*::::::::::::::::::::::::::::::::: PORTFOLIOS :::::::::::::::::::::::::::::::::*/

	    editingProject : function(){
	      return $('form#form_project_createdit > input[type=hidden]').length;
	    },

		initProjectCoverForm : function(){
		  method = DMSTK.editingProject() ? 'PUT' : 'POST';
		  DMSTK.setupUploadIframe('form_project_createdit', 'cover', 'project_thumbnail', method);
		},

		NEW_ITEM : 0,
		MAX_ITEM_WEIGHT : 0,
		MIN_ITEM_WEIGHT : 9999999,

		initPortfolioCreateEditForm : function() {
			// Content functions 
			if (DMSTK.editingProject()) {
				DMSTK.addMultimediaContent('fieldset.insert_edit_field h3');
			
				$('fieldset.add_project_content').css('display', 'none');
			
				//Item action functions
				DMSTK.calculateMaxItemWeight();
				//DMSTK.calculateMinItemWeight();
				DMSTK.addProjectItemActions();
				DMSTK.addWeightSetterOnSubmit();
				
				//Asyncrhonous upload
				DMSTK.loadIframe();
				DMSTK.addAsynchronousUpload();
			
			}
		},
		
		// Reassigns item weights based in HTML order before submission
		addWeightSetterOnSubmit : function() {
			$('#form_project_createdit').submit( function() {
				$('[name*="_items["][name*="[position]"]').map( 
																function(index, elem){ 
																	$(elem).val(index+1); 
																} 
				);
				return true;
			});			
		},
		
		calculateMaxItemWeight : function() {
			$('input.project_item_weight').each(function() {
				if (parseInt($(this).attr('value')) > DMSTK.MAX_ITEM_WEIGHT) DMSTK.MAX_ITEM_WEIGHT = parseInt($(this).attr('value'));
			});
		},
		
		
		calculateMinItemWeight : function() {
			$('input.project_item_weight').each(function() {
				if (parseInt($(this).attr('value')) < DMSTK.MIN_ITEM_WEIGHT) DMSTK.MIN_ITEM_WEIGHT = parseInt($(this).attr('value'));
			});
		},
				
		
		addMultimediaContent : function(selector) {
		 	$(selector).after('<div id="insert_content"><p><strong>Insertar contenidos</strong></p><ul><li><a href="#" class="IR" id="insert_text_button"><span>Insertar texto</span></a></li><li><a href="#" class="IR" id="insert_image_button"><span>Insertar imagen</span></a></li><li><a href="#" class="IR" id="insert_video_button"><span>Insertar video</span></a></li><li><a href="#" class="IR" id="color_picker_button"><span>Personalizar colores</span></a></li></ul></div>');
		 	
		 	$('fieldset#color_picker').css('display', 'none');
		 	
		 	$('a#color_picker_button').click(function() {
		 		$('fieldset#color_picker').toggle();
		 		return false;
		 	});
		 	
		 	$('a#insert_text_button').click(function() {
		 		DMSTK.addTextContent();
		 		return false;
		 	});
		 	
		 	$('a#insert_image_button').click(function() {
		 		DMSTK.addImageContent();
		 		return false;
		 	});
		 	
		 	$('a#insert_video_button').click(function() {
		 		DMSTK.addVideoContent();
		 		return false;
		 	});
		},
		
		addTextContent : function() {
			$.ajax({
				url: "/ajax-partial/projects/new_text_item",
				dataType: "html",
				
				success : function(data) {
					DMSTK.NEW_ITEM++;
					DMSTK.MAX_ITEM_WEIGHT++;
					DMSTK.MIN_ITEM_WEIGHT--;
					dataObject = $(data);
					dataObject.attr('id', 'new_item_'+DMSTK.NEW_ITEM);
					dataObject.find('input.project_item_weight').attr('value', DMSTK.MIN_ITEM_WEIGHT);
					
					//$('fieldset.insert_edit_field div.form_field').append(dataObject);
					$('fieldset.insert_edit_field div.form_field fieldset#color_picker').after(dataObject);
					DMSTK.addProjectItemActions('new_item_'+DMSTK.NEW_ITEM);
					DMSTK.addAsynchronousUpload();
				}
			});			
		},
		
		addImageContent : function() {
			$.ajax({
				url: "/ajax-partial/projects/new_image_item",
				dataType: "html",
				
				success : function(data) {		
					DMSTK.NEW_ITEM++;
					DMSTK.MAX_ITEM_WEIGHT++;
					DMSTK.MIN_ITEM_WEIGHT--;
					dataObject = $(data);
					dataObject.attr('id', 'new_item_'+DMSTK.NEW_ITEM);
					dataObject.find('input.project_item_weight').attr('value', DMSTK.MIN_ITEM_WEIGHT);

					//$('fieldset.insert_edit_field div.form_field').append(dataObject);
					$('fieldset.insert_edit_field div.form_field fieldset#color_picker').after(dataObject);
					DMSTK.addProjectItemActions('new_item_'+DMSTK.NEW_ITEM);
					DMSTK.addAsynchronousUpload();
				}
			});		
		},
		
		addVideoContent : function() {
			$.ajax({
				url: "/ajax-partial/projects/new_video_item",
				dataType: "html",
				
				success : function(data) {
					DMSTK.NEW_ITEM++;
					DMSTK.MAX_ITEM_WEIGHT++;
					DMSTK.MIN_ITEM_WEIGHT--;
					dataObject = $(data);
					dataObject.attr('id', 'new_item_'+DMSTK.NEW_ITEM);
					dataObject.find('input.project_item_weight').attr('value', DMSTK.MIN_ITEM_WEIGHT);

					//$('fieldset.insert_edit_field div.form_field').append(dataObject);
					$('fieldset.insert_edit_field div.form_field fieldset#color_picker').after(dataObject);
					DMSTK.addProjectItemActions('new_item_'+DMSTK.NEW_ITEM);
					DMSTK.addAsynchronousUpload();
				}
			});					
		},

		addProjectItemActions : function(new_item_id) {
						
			$('div.project_content_item' + (new_item_id? '#' + new_item_id : '') + ' fieldset.project_item_actions').css('display', 'none');
			$('div.project_content_item' + (new_item_id? '#' + new_item_id : '') + ' fieldset.external_video label.project_item_weight').css('display', 'none');

			$('div.project_content_item' + (new_item_id? '#' + new_item_id : '')).each(function(i) {
				$(this).prepend('<div class="project_item_actions"><ul><li><a href="#" class="IR order_up"><span>Subir</span></a></li><li><a href="#" class="IR order_down"><span>Bajar</span></a></li><li><a href="#" class="IR order_delete"><span>Borrar</span></a></li></ul></div>');
				
				$(this).find('a.order_delete').click(function() {
					if (confirm('¿Seguro que quieres eliminar este contenido del proyecto?')) {
						if ($(this).parents('.project_content_item.project_content_new_text').length || $(this).parents('.project_content_item.project_content_new_image').length || $(this).parents('.project_content_item.project_content_new_video').length ) {
							$(this).parents('.project_content_item').remove();	
						} else {
							$(this).parents('.project_content_item').find('label.project_item_actions_delete input[type="checkbox"]').attr('checked', true);
							$(this).parents('.project_content_item').fadeOut();
						}
					}
					return false;
				});
				
				$(this).find('a.order_up').click(function() {
					
					if ($(this).parents('.project_content_item').prevAll('.project_content_item').eq(0).length) {
						oldWeight = $(this).parents('.project_content_item').find('input.project_item_weight').attr('value');
						newWeight = $(this).parents('.project_content_item').prevAll('.project_content_item').eq(0).find('input.project_item_weight').attr('value');
						
						$(this).parents('.project_content_item').find('input.project_item_weight').attr('value', newWeight);
						$(this).parents('.project_content_item').prevAll('.project_content_item').eq(0).find('input.project_item_weight').attr('value', oldWeight);
											
						$(this).parents('.project_content_item').prevAll('.project_content_item').eq(0).before($(this).parents('.project_content_item'));
						
					}
	
					return false;
				});
				
				$(this).find('a.order_down').click(function() {

					if ($(this).parents('.project_content_item').nextAll('.project_content_item').eq(0).length) {
						oldWeight = $(this).parents('.project_content_item').find('input.project_item_weight').attr('value');
						newWeight = $(this).parents('.project_content_item').nextAll('.project_content_item').eq(0).find('input.project_item_weight').attr('value');
						
						$(this).parents('.project_content_item').find('input.project_item_weight').attr('value', newWeight);
						$(this).parents('.project_content_item').nextAll('.project_content_item').eq(0).find('input.project_item_weight').attr('value', oldWeight);
						
						$(this).parents('.project_content_item').nextAll('.project_content_item').eq(0).after($(this).parents('.project_content_item'));
					}
					
					return false;
				});
				
			});
		},
		
		UPLOADING : false,
		
		UPLOAD_QUEUE : new Array(),
		
		addAsynchronousUpload : function() {
			
			$('form#form_project_createdit').find('input[type=file]:not(#cover)').each(function() {
				
				$(this).bind('change', function(object) {
					
					newFormId = $(this).parents('div.project_content_item').attr('id');
				
					if (jQuery.inArray('form#upload_form_'+newFormId, DMSTK.UPLOAD_QUEUE) >= 0 || $('form#upload_form_'+newFormId).length > 0) return false;
					
					$(this).unbind('change');
	
					// Create form				
					newForm = '<form action="'+$('form#form_project_createdit').attr('action')+'/add_temp_item" target="upload_frame" method="'+$('form#form_project_createdit').attr('method')+'" enctype="'+$('form#form_project_createdit').attr('enctype')+'" accept-charset="'+$('form#form_project_createdit').attr('accept-charset')+'" id="upload_form_'+newFormId+'" class="'+newFormId+' form_hidden"><fieldset><input type="hidden" name="_method" value="PUT" /></fieldset></form>';
					
					$('form#form_project_createdit').after(newForm);			
					
					// Move the input file element, $(this) changes its position
					$('form#upload_form_'+newFormId+' fieldset').append($(this));

					$('form#upload_form_'+newFormId+' fieldset').append('<input type="hidden" name="div_item_id" value="'+newFormId+'" />');
							
					if (!DMSTK.UPLOADING) {
						DMSTK.UPLOADING = true;
						$('div#'+newFormId).find('fieldset.upload_project_content div').append('<div class="uploading"><span>Uploading...</span></div>');
						// Submit the form
						$('form#upload_form_'+newFormId).submit();
						// Remove form
						$('form#upload_form_'+newFormId).remove();
					}
					else {
						$('div#'+newFormId).find('fieldset.upload_project_content div').append('<div class="waiting"><span>Waiting...</span></div>');
						DMSTK.UPLOAD_QUEUE.push('form#upload_form_'+newFormId);
					}
					
				});
				
			});
			
		},
		
		loadIframe : function() {
			
			$('form#form_project_createdit').after('<iframe id="upload_frame" name="upload_frame"></iframe>');
			$('iframe#upload_frame').css('display', 'none');
			
			$('iframe#upload_frame').load(function() {
				
				response = $('iframe#upload_frame').contents().find('body').html();
				item_id = $('iframe#upload_frame').contents().find('body div.project_content_item').attr('id');			
				
				if (item_id != undefined) {
					$('div#'+item_id).replaceWith(response);
					DMSTK.addProjectItemActions(item_id);
					DMSTK.addAsynchronousUpload();
					
					DMSTK.UPLOADING = false;
					DMSTK.callUploadQueue();
				}

			});	
		},
		
		callUploadQueue : function() {
			
			newForm = DMSTK.UPLOAD_QUEUE.shift();
			
			if (newForm == undefined) return false;
			
			if (!DMSTK.UPLOADING) {
				DMSTK.UPLOADING = true;
				
				$('#'+$(newForm).attr('class').substring(0, $(newForm).attr('class').indexOf(' '))).find('div.waiting').replaceWith('<div class="uploading"><span>Uploading...</span></div>');
				
				// Submit the form
				$(newForm).submit();
				// Remove form
				$(newForm).remove();
			}
			else {
				$('#'+newForm.attr('class')).find('div').append('<div class="waiting"><span>Waiting...</span></div>');
				DMSTK.UPLOAD_QUEUE.push('form#upload_form_'+$(this).parents('div.project_content_item').attr('id'));
			}
		},
		
		toggleProjectInfo : function() {
			if ($('div.project_info').length) {
				$('div.project_info').append('<ul class="show_project_info"><li class="view_info"><a href="#" class="IR"><span>Ver más información</span></a></li><li class="close_info"><a href="#" class="IR"><span>Cerrar más información</span></a></li></ul>');
				
				$('ul.show_project_info li.view_info a').click(function() {
					if ($('div.project_info div.project_columns').css('display') == 'block') {
						$('div.project_info div.project_columns').slideUp('fast');
						$('li.close_info').fadeOut();	
					}
					else {
						$('div.project_info div.project_columns').slideDown('fast');
						$('li.close_info').fadeIn();					
					}
					return false;
				});
				
				$('ul.show_project_info li.close_info a').click(function() {
					$('div.project_info div.project_columns').slideUp('fast');
					$('li.close_info').fadeOut();
					return false;
				});
				
				$('div.project_info div.project_columns, li.close_info').css('display', 'none');
			}	
		},
		
        /*::::::::::::::::::::::::::::::::: AJAXIFY :::::::::::::::::::::::::::::::::*/
        submitAndRemove: function() {
            $('.submit_and_remove').submit(function(e) {
                e.preventDefault();
                var $form = $(this),
                    $item = $form.parents(".item").fadeOut(function() {
                        if ($('#main_content .item:visible').length === 0) {
                            $('#main_content').append(
                                '<div class="content_module feedback_message to_hell_with_rounded_corners">' +
                                  '<div class="feedback_container">' +
                                    '<h2 class="feedback_title">Te has ganado un coffee break</h2>' +
                                    '<div class="feedback_content">' +
                                      '<p>No hay nada pendiente.</p>' +
                                    '</div>' +
                                  '</div>' +
                                '</div>');
                        }
                    });
                $.ajax({
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: $form.serialize(),
                    success: function(e) {
                    },
                    error: function(e) {
                        $item.fadeIn();
                        $('#main_content .message').remove();
                        alert("Error submitting form: "+e);
                    }
                })
            });
        }

}

$(document).ready(function() {
	if (document.getElementById) {
	  DMSTK.initCufon();
	  DMSTK.datesAgo(DMSTK_NOW);
		DMSTK.roundeMeNow(); 
		if(!$.browser.msie) DMSTK.createDock();
		DMSTK.prepareMarkInputsLink();
		DMSTK.stickMyForms();
		DMSTK.autoPopup();
		DMSTK.prepareQuotes();
		DMSTK.labelifyEmail();
		if(!($.browser.msie && parseInt($.browser.version) == 6)) DMSTK.prepareConfirmationFieldset();
		if(!($.browser.msie && parseInt($.browser.version) == 6)) DMSTK.submitToButton();
		DMSTK.initFilters();
		//DMSTK.stepsModule();
		DMSTK.initPortfolioCreateEditForm();
		DMSTK.initProjectCoverForm();
		DMSTK.initPortfolioCoverForm();
		DMSTK.toggleProjectInfo();
		DMSTK.submitAndRemove();
	}
});

window.onload = function() {
	if(!($.browser.msie && parseInt($.browser.version) == 6)) DMSTK.preparePaginator();
}

$(window).scroll(function () {
	if(!($.browser.msie && parseInt($.browser.version) == 6)) DMSTK.movePaginator();
});
