var itemStock = 0;
$(document).ready( function(){
	// remove non digit value for the quantity entered
	$("input#item_qty").change(function() {
		var re=/\D/g; // remove non digit char
		s = $(this).val(); //  get value
		s = s.replace(re,''); // exec regex
		$(this).val((s == '') ? 1 : s ); // set 1 like default value
	});

	if($('#stockcontrol').val() != 'go' && $('#stockcontrol').length > 0){
	    alert(reachmaxTxt);
	    $('#item_qty').val(stockjustadd);
	    $('#stockcontrol').val('go');
	}

    $('#btnAddToCart').click( function(){
        if($('#item_id').val() != 0 || $('#item_collection_id').val() != 0)//Verifie qu'il y ai bien qqchose de selectionné
        {
        	$('#frmSubmitItem').submit();
            return false;
        }
    });

    $('#btnPrevCharacter').click( function(){
        MoveCharacterPosition(-1);
        UpdateController__Personnage();
        //InvestigateCreations('......');//Enlevé par Vince car création du path directement dans UpdateController_Perso sans passer par Ajax
    });

    $('#btnNextCharacter').click( function(){
        MoveCharacterPosition(+1);
        UpdateController__Personnage();
        //InvestigateCreations('......');
    });

    $('#btnEditCancel').click( function(){
        $('#frmEditCancel').submit();
    });

    $('#btnEditSave').click( function(){

        var action = $('#frmSubmitItem').attr('action').replace('Add','Edit');
        $('#frmSubmitItem').attr('action', action)
        $('#frmSubmitItem').submit();
    });

    $('#btnZoom').click( function(event){
        var path = $('#itemPhoto').attr('src').replace('renders','renders_zoom');
        Tip('<img src="'+path+'" />',DELAY,0,FOLLOWMOUSE,false,CLICKCLOSE,true,TITLE,false,CLOSEBTN,false, TITLEBGCOLOR, 'black', TITLEFONTCOLOR, 'white', BGCOLOR, 'white', FONTCOLOR, 'black', WIDTH, 400, HEIGHT, 327);
    });

    /*$('#KettoItemEditor').mouseout( function(event){
        UnTip();
    });*/

    SetMode(editorMode);
    SetShoppable(editorShoppable);


    InvestigateCreations(46);


});

function InvestigateCreations(line){
	//alert(line);
    /*
    Selon le contexte du ItemEditor, obtenir un render path, et les valeurs possibles pour les diff�rents contr�leurs

    "only_category_id" sert � pr�ciser qu'on sait la cat�gorie, et rien d'autre. Le script AJAX ignore tout le reste dans ce cas.

   */
   // alert(selected_item_id);
	if( (line == 299) && !selected_character_id) {
		return false;
	}
	// on cache le bouton ajouter a mon panier si la collection n'est pas choisie
	if( (selected_collection_id == 0) || (selected_item_id == 0) ) {
		$("#systemOptions_Add").hide();
		$("#controleurCustomText").hide();
		$("#controleurQte").hide();
		$("#systemInfo_sysmsg").hide();
		$("#systemInfo_CharacterName").hide();

	}
	else {
		$("#systemOptions_Add").show();
		if(selected_category_id == 1)$("#controleurCustomText").show();
		$("#controleurQte").show();
		//$("#systemInfo_sysmsg").show();
		if(selected_category_id == 1 || selected_category_id == 3 || selected_category_id == 4)$("#systemInfo_CharacterName").show();
		itemStock = getSelectedStock(selected_item_id);
	}
    $.ajax({
        url: 'CartAjax_InvestigateCreations',
        data:     params = 'only_category_id=' + only_category_id + '&category_id=' + selected_category_id + '&collection_id=' + selected_collection_id + '&item_id=' + selected_item_id + '&color_id=' + selected_color_id + '&size_id=' + selected_size_id + '&character_id=' + selected_character_id,
        type: 'GET',

        dataType: 'json',
        success: function(json){

            //dig�rer le contexte dans nos variables globales
            available_collections = json.controller_context.collections;
            available_items = json.controller_context.items;
            available_colors = json.controller_context.colors;
            available_sizes = json.controller_context.sizes;
            available_characters = json.controller_context.characters;

            //selected_... cleanup
            selected_character_id = 0;

	    selected_color_id = json.render.color_id;

            //mettre à jour le visuel
            $('#KettoItemEditor_photo').html('<img id="itemPhoto" src="'+ json.render.path_full +'" alt="'+ json.render.filename +'" />');
	    //$('#systemInfo_sysmsg').html(json.render.filename);


            //mettre à jour les menus, aka "contrôleurs"
            UpdateAllControllers();

            //mettre à jour les événements bindés sur les menus
            BindAllControllers();
        }
    });

}

function UpdateAllControllers(){
    //On assume...
    //  -que tous les arrays available_... ont les bonnes valeurs dedans.
    //  -que toutes les valeurs selected_... sont sett�es et valides.

    UpdateController__Categorie(selected_category_id);
    UpdateController__Item(selected_item_id);
    UpdateController__Collection(selected_collection_id);
    UpdateController__Size(selected_size_id);
    UpdateController__Couleur(selected_color_id);
    UpdateController__Personnage(selected_character_id);
    UpdateController__CustomText(selected_category_id);
    UpdateController__Desc(selected_item_id);
}

function BindAllControllers(){
    /*
    Attache les évènements aux controlleurs qui peuvent changer en cours de route (il faut alors les rafraîchir)
    */

    $('#item_category_id').unbind();
    $('#item_category_id').change( function(){

        selected_category_id = $('#item_category_id option:selected').attr('value');


        //cleanup some other selectors
        selected_item_id = 0;
        selected_collection_id = 0;
        selected_color_id = 0;
        selected_size_id = 0;

	//Pour gérer le changement automatique de collection
	collectionChangeMarker = 0;

        // On ne tient compte que de la catégorie et c'est voulu: ainsi tous les contrôleurs seront réinitialisés.
        InvestigateCreations(133);

    });

    $('#item_id').unbind();
    $('#item_id').change( function(){
        selected_item_id = $('#item_id option:selected').attr('value');

        //cleanup some other selectors
        //selected_collection_id = ($(available_collections).length == 1 ? $(available_collections)[0].id : 0);//Ne fonctionne pas avec bijoux
        selected_collection_id = 0;
	selected_character_id = 0;
        selected_character_position = 0;

	//Pour gérer le changement automatique de collection
	collectionChangeMarker = 1;

        selected_size_id = 0;
        selected_color_id = 0;

        InvestigateCreations(153);


    });

    $('#item_collection_id').unbind();
    $('#item_collection_id').change( function(){
        selected_collection_id = $('#item_collection_id option:selected').attr('value');

	//Pour gérer le changement automatique de collection
	collectionChangeMarker = 0;

        selected_character_id = 0;
        selected_character_position = 0;
        InvestigateCreations(167);
    });

    $('.ItemColor input').unbind();
    $('.ItemColor input').click(function(event){
        selected_color_id = $('.ItemColor input:checked').attr('value');
        InvestigateCreations(173);
    });

    $('.ItemSize input').unbind();
    $('.ItemSize input').click(function(event){
        selected_size_id = $('.ItemSize input:checked').attr('value');
        InvestigateCreations(179);
    });

}

function SetSysMSG(msg){
    //$('#systemInfo_sysmsg').html(msg);
}

function ResetSysMSG(msg){
    //$('#systemInfo_sysmsg').html('&nbsp;');
}

function isIE(){//return true si IE
    return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function UpdateController__Categorie(selected_id){
    //cleanup
    $('#item_category_id').children().remove();

    $('#controleurPrice').addClass('hidden');

    //feed select box w/ options

    $(available_categories).each( function(i, category){
	option = document.createElement('option');
	$(option).attr('id', 'category_' + category.id);
	$(option).attr('value', category.id);
	$(option).html( category.name );
	//selected?
	if( parseInt(selected_id) == category.id )
	    $(option).attr('selected','selected');

	$('#item_category_id').append(option);
    });
    $('#controleurCategorie').removeClass('hidden');
}

function UpdateController__Item(selected_id){
    //NO categories ==> hide controller
    if( available_items.length == 0 ){
	$('#controleurItem').addClass('hidden');
	return false;
    }

    //cleanup
    $('#item_id').children().remove();

    //On ajoute une option par defaut suggérant de faire un choix !!! Obligé à cause du trop grand nombre de possibilités!!
    option = document.createElement('option');
	$(option).attr('id', 'item_0');
	$(option).attr('value', 0);
	$(option).html( topchoiceitem );
	$('#item_id').append(option);

    //feed select box w/options
    $(available_items).each( function(i, item){

	option = document.createElement('option');
	$(option).attr('id', 'item_'+item.id);
	$(option).attr('value', item.id);
	$(option).html( item.name );

	//selected ?
	if( parseInt(selected_id) == item.id )
	{
	    $(option).attr('selected','selected');
	    selected_item_code = item.code;
	    $('#controleurPrice').removeClass('hidden');
	    $('#price').html(item.price);
	}
	$('#item_id').append(option);
    });

    $('#controleurItem').removeClass('hidden');
}

function UpdateController__Collection(selected_id){

    //$('#item_collection_id').unbind();

    //NO categories ==> hide controller
    if( available_collections.length == 0 ){
	$('#controleurCollection').addClass('hidden');
	return false;
    }

    //cleanup
    $('#item_collection_id').children().remove();

    //On ajoute une option par defaut suggérant de faire un choix !!! Obligé à cause du trop grand nombre de possibilités!!
    option = document.createElement('option');
	$(option).attr('id', 'collection_0');
	$(option).attr('value', 0);
	$(option).html( topchoicecollection );
	$('#item_collection_id').append(option);

    //feed select box w/options
    $(available_collections).each( function(i, collection){

    	option = document.createElement('option');
		$(option).attr('id', 'collection_'+collection.id);
		$(option).attr('value', collection.id);
		$(option).html( collection.name );

		//selected ?

		if( parseInt(selected_id) == collection.id )
			$(option).attr('selected','selected');

		$('#item_collection_id').append(option);
    });

    if( available_collections.length == 1 && collectionChangeMarker == 1 ){
	$('#item_collection_id').val($("#item_collection_id option:last").val());
	$('#item_collection_id').change();
	selected_collection_id = $(available_collections)[0].id;
	collectionChangeMarker == 0;
	$('#controleurCollection').addClass('hidden');
	InvestigateCreations(299);
    }
    /*if( available_collections.length == 1 && $('#item_id').val() > 0 ){
    	$('#item_collection_id').val($("#item_collection_id option:last").val());
	$('#item_collection_id').change();
    }*/
    //Si rien de selectionner (id a 0), on selectionne le premier de la drop liste. Ne marche pas a cause que quand on change d'item on doit remettre les collections à zero.
    //if(selected_id == 0) selected_collection_id = $("#item_collection_id option:first").val();

    if(available_collections.length != 1)
	$('#controleurCollection').removeClass('hidden');

}

function UpdateController__Size(selected_id){

    //NO categories ==> hide controller
    if( available_sizes.length == 0 ){
	$('#controleurSize').addClass('hidden');
	$('#controleurSize div').children().remove();
	return false;
    }

    //cleanup
    $('#controleurSize div').children().remove();

    //selected_ default if none
    if( selected_id == 0 ){
        selected_id = available_sizes[0]['id'];
        selected_size_id = selected_id;
    }


    //feed select box w/options
    $(available_sizes).each( function(i, size){

	//container span w/ size name
	span = document.createElement('span');
	$(span).addClass('ItemSize');
	$(span).addClass('RadioSize');
	$(span).html( '<span>' + size.name + '</span>' );

	//radio button.
	if(isIE())
	{
	    if( parseInt(selected_id) == size.id )
		radio=document.createElement('<input type="radio" id="item_size" name="item_size" value="'+size.id+'" checked="checked" />');
	    else
		radio=document.createElement('<input type="radio" id="item_size" name="item_size" value="'+size.id+'" />');
	}
	else
	{
	    radio = document.createElement('input');
	    $(radio).attr('value', size.id);
	    $(radio).attr('type', 'radio');
	    $(radio).attr('id', 'item_size');
	    $(radio).attr('name', 'item_size');
	    if( parseInt(selected_id) == size.id )
		$(radio).attr('checked','checked');
	}

	$(span).append(radio);
	$('#controleurSize div').append(span);
    });
    if(selected_category_id == 5){
	$('#controleurSize').addClass('hidden');
    }
    else
        $('#controleurSize').removeClass('hidden');
}

function UpdateController__Couleur(selected_id){
    //NO categories ==> hide controller
    if( available_colors.length == 0 ){
	$('#controleurCouleur').addClass('hidden');
	$('#controleurCouleur div').children().remove();
	return false;
    }

    //cleanup
    $('#controleurCouleur div').children().remove();

    //selected_ default if none (todo: ou si on change d'item mais la couleur n'est pas la)
    if( selected_id == 0 ){
        selected_id = available_colors[0]['id'];
        selected_color_id = selected_id;
    }

    //feed select box w/options
    $(available_colors).each( function(i, color){

	//parent span w/ color name
	span = document.createElement('span');
	$(span).addClass('ItemColor');
	$(span).addClass('RadioSize');


	//color square to know what you're clicking on
	span_color = document.createElement('span');
	if(color.rgb.substring(0,1) == '#')
	{
	    $(span_color).attr('style', 'background-color:'+color.rgb);
	    $(span_color).addClass('imgcolor');
	    $(span).append(span_color);
	}
	else
	{
	    $(span_color).attr('style', 'background: url('+sPathAbs+'/img/shared/color/'+color.rgb+'.png) center center no-repeat');
	    $(span_color).addClass('imgcolor');
	    $(span).append(span_color);
	}

	//radio button.
	if(isIE())
	{
	    if( parseInt(selected_id) == color.id )
		radio=document.createElement('<input type="radio" id="item_color" name="item_color" value="'+color.id+'" checked="checked" />');
	    else
		radio=document.createElement('<input type="radio" id="item_color" name="item_color" value="'+color.id+'" />');
	}
	else
	{
	    radio = document.createElement('input');
	    $(radio).attr('value', color.id);
	    $(radio).attr('type', 'radio');
	    $(radio).attr('id', 'item_color');
	    $(radio).attr('name', 'item_color');
	    if( parseInt(selected_id) == color.id )
		$(radio).attr('checked','checked');
	}

	$(span).append(radio);

	$('#controleurCouleur div').append(span);
    });
    $('#controleurCouleur').removeClass('hidden');
}


function UpdateController__Personnage(selected_id){

    //NO categories ==> hide controller
    if( available_characters.length == 0 ){
	$('#controleurPersonnage').addClass('hidden');
        $('#systemInfo_CharacterName').addClass('hidden');
	$('#character_id').val('');
	return false;
    }
    else
    {
	//Ne pas afficher les caractère tant que collection et item  sont à 0
	if(selected_collection_id != 0 && selected_item_id != 0)
	{
	    //update character count
	    $('#systemInfo_CharacterCount').html( (selected_character_position+1) + '/' + available_characters.length);
	    $('#character_position').val(selected_character_position);

	    //update character ID selon position
	    selected_character_id = available_characters[selected_character_position]['id'];


	    //field in case of cart add
	    $('#character_id').val( selected_character_id );


	    $('#character_name').html( available_characters[selected_character_position]['name'] );

	    $('#KettoItemEditor_photo').html('<img id="itemPhoto" src="media/shared/renders/'+ selected_item_code + '-' + available_characters[selected_character_position]['code'] +'.jpg" alt="'+ available_characters[selected_character_position]['name'] +'" />');

	    //$('#systemInfo_sysmsg').html(selected_item_code+'-' + available_characters[selected_character_position]['code']+'.jpg');

	    $('#controleurPersonnage').removeClass('hidden');
	    $('#systemInfo_CharacterName').removeClass('hidden');
	}
    }

}

function UpdateController__CustomText(selected_id){
    //Si Céramique, on affiche sinon rien et vide
    if(selected_category_id == 1)
    {
	$('#controleurCustomText').removeClass('hidden');
    }
    else
	{
	    $('#controleurCustomText').addClass('hidden');
	    $('#item_custom_text').val('');
	}

}

function getSelectedStock(selected_id){
	var thisstock = 0;
    $(available_items).each( function(i, item){
	if( parseInt(selected_id) == item.id )
	{
		thisstock = item.stock;
	}
    });
	return thisstock;

}

function UpdateController__Desc(selected_id){

    $(available_items).each( function(i, item){
	if( parseInt(selected_id) == item.id )
	{
	    $('#KettoItemEditor_description').html(item.desc);
	    $('#KettoItemEditor_description').removeClass('hidden');
	}
    })
    if(selected_id == 0)
	$('#KettoItemEditor_description').addClass('hidden');

}



function SetMode(mode){
    switch(mode){
	case 'edit':
            $('#systemOptions_Edit').removeClass('hidden');
	    $('#titre_edition').html("Modification de l'article");
	    break;

	case 'add':
	default:
            $('#systemOptions_Edit').addClass('hidden');
	    $('#titre_edition').html('Un peu de Shopping!');
	    break;
    }

    $('#titre_edition').removeClass('hidden');
}

function SetShoppable(shoppable){

    if(shoppable){
        $('#systemShoppingTools').removeClass('hidden');
        $('#systemOptions_Add').removeClass('hidden');

    } else{
        $('#systemShoppingTools').addClass('hidden');
        $('#systemOptions_Add').addClass('hidden');

    }
}

function MoveCharacterPosition(direction){
    // "direction" pour naviguer entre les personnages: -1 recule, +1 avance, 0 reste l�.

    //on additionne la direction peu importe les cons�quences...
    selected_character_position += direction;

    //...ensuite on corrige les �ventuels d�bordement hors-bornes
    if(selected_character_position < 0) selected_character_position = available_characters.length - 1;
    if(selected_character_position == available_characters.length) selected_character_position = 0
}
