'use strict';

/**
@author María Andrea Cruz Blandón
@module sgSequence
@description This module manages everything relative to a sequence element, it has all the 
methods to work with events and initialize the element.
**/

define(['jquery', 'sgButtonsManager'], function($, sgButtonsManager){

	var app = {};

	app.init = function(){
		$("[data-sg-id=elem-sequence]")
		.each(function(i, elem) {
			var $allElements = $(elem).children();
			var $btnElements = $(elem).children("[data-sg-id=btn-sequence]");


			var $together = $(elem).attr("data-sg-together");
			$together = $together == undefined? false : ($together == "true"? true : false);


			$allElements.hide();

			//sg-together is true? so the btn and item is showed at same time
			if($together){
				$allElements.eq(0).show();
				$allElements.eq(1).show();	
			}else{//sg-together is false? so just the btn is showed
				$allElements.eq(0).show();
			}

			$btnElements.each(function(j, btn){
				sgButtonsManager.btnInit(btn);
				$(btn).attr("data-sg-status","close");
				$(btn).click(nextStep);
			});
		});
	};

	function nextStep(){
		var $status = $(this).attr("data-sg-status");

		var $together = $(this).parent().attr("data-sg-together");
		$together = $together == undefined? false : ($together == "true"? true : false);

		var $nextBtn = $(this).next().next();
		var $nextItem = $together? $nextBtn.next(): $(this).next();
		//close so open the next step
		if($status == "close"){
			//Only has the click event the btn which triggered the event and the next btn.
			$(this).prevAll().unbind("click").css("cursor", "auto");
			$(this).bind("click").css("cursor", "pointer");
			//Could be a button or a final item.		
			$nextBtn.attr("data-sg-id") == "btn-sequence"? $nextBtn.bind("click").css("cursor", "pointer"): $nextBtn.css("cursor", "auto");
			$(this).attr("data-sg-status","open");

			//together?
			if($together){
				$nextBtn.add($nextItem).fadeIn(200);
			}else{
				$nextItem.fadeIn(200);
				$nextBtn.fadeIn(500);
			}
		}else{//open so close the before step
			var $prevBtn = $(this).prev().prev();
			$(this).attr("data-sg-status","close");
			$prevBtn.bind("click", nextStep).css("cursor", "pointer");

			//together?
			if($together){
				$nextBtn.add($nextItem).fadeOut(200);
			}else{
				$nextBtn.fadeOut(200);
				$nextItem.fadeOut(500);
			}
			
		}
	};

	return app;

});