/*
 * Create AuctionCategoryBrowser
 */
YAHOO.namespace("AuktionMaster");
YAHOO.AuktionMaster.AuctionCategoryBrowser = function( data ) {
	// Init based Variables
	var tree, panel;
	// Set Variables
	var category_prefix = data['category_prefix'];
	var ebay_attribtes = data['ebay_attribtes'];
	var channel_id = data['channel_id'];
	var sub_channel_id = data['sub_channel_id'];
	var offer_type_id = data['offer_type_id'];
	var item_id = data['item_id'];
	var request_uri = data['request_uri'];
	var request_query = data['request_query'];
	// Build 
	buildTree();
	buildPanel();
	
	if (channel_id == 1){
		// Lade die Ebayattribute beim ersten Start
		loadEbayAttributes( document.getElementById( category_prefix+'_id' ).value );
	}
	
	if (channel_id == 4){
		//load AmazonMwsAttributes with first start
		loadAmazonMwsAttributes( document.getElementById( category_prefix+'_id' ).value );
	}
	
	// flags for showing progress icon
	var bLoadingName       = false;
	var bLoadingAttributes = false;
	
	// Methoden
	function clickNode( node ) {
		document.getElementById( category_prefix+'_name' ).innerHTML = resolvCategoryName( node ) + ' (' + node.data.id + ')';
		document.getElementById( category_prefix+'_id' ).value = node.data.id;
		if( channel_id == 1 ) { // Ebay
            // synchronize the input field
            var field = document.getElementById( category_prefix+'_inputIdField' );
            if(field){
                field.value = node.data.id;
            }
            // load all attributes (additional form fields) from ajax call
			loadEbayAttributes( node.data.id );
		} else {
			if(channel_id == 4 ){ // AmazonMws
			// synchronize the input field
            var field = document.getElementById( category_prefix+'_inputIdField' );
            if(field){
                field.value = node.data.id;
            }
            // load all attributes (additional form fields) from ajax call
			loadAmazonMwsAttributes( node.data.id );
			}else {
				hidePanel();
			}
		}
	}
	function resolvCategoryName( node ) {
		var name = node.data.name;
		if ( node.depth > 0 ) {
			name = resolvCategoryName( node.parent ) + ' / ' + name;
		}
		return name;
	}
	function addNode( parent, node_data ) {
		if( node_data.getElementsByTagName('count')[0].firstChild.data == 0 ) {
			var attr = {
				id:node_data.getElementsByTagName('category_id')[0].firstChild.data,
				name:node_data.getElementsByTagName('name')[0].firstChild.data,
				label:node_data.getElementsByTagName('name')[0].firstChild.data
			}
			var node = new YAHOO.widget.TextNode( attr, parent, false );
			if( node_data.getElementsByTagName('expand')[0].firstChild.data == 1 ) {
				document.getElementById( category_prefix+'_name' ).innerHTML = resolvCategoryName( node ) + ' (' + node.data.id + ')';
			}
			node.onLabelClick = clickNode;
		} else {
			if( node_data.getElementsByTagName('expand')[0].firstChild.data == 1 ) {
				var expand = true;
			} else {
				var expand = false;
			}
			var attr = {
				id:node_data.getElementsByTagName('category_id')[0].firstChild.data,
				name:node_data.getElementsByTagName('name')[0].firstChild.data,
				label:node_data.getElementsByTagName('name')[0].firstChild.data+' ('+node_data.getElementsByTagName('count')[0].firstChild.data+')'
			}
			var node = new YAHOO.widget.TextNode( attr, parent, expand );
		}
	}
	function addNodes( parent, response ) {
		var categories = response.getElementsByTagName('category');
		for( var i = 0; i < categories.length; i++ ) {
			addNode( parent, response.getElementsByTagName('category')[i] );
		}
	}
	function loadRootCategories() {
		var request = YAHOO.util.Connect.asyncRequest( 'POST', request_uri, { success:loadRootCategoriesSuccessHandler }, request_query+'categories&channel_id='+channel_id+'&sub_channel_id='+sub_channel_id+'&old_category_id='+document.getElementById( category_prefix+'_id' ).value );
	}
	function loadRootCategoriesSuccessHandler( o ) {
		addNodes( tree.getRoot(), o.responseXML.documentElement );
		tree.draw();
	}
	function loadCategorySuccessHandler( o ) {
		addNodes( o.argument.parent, o.responseXML.documentElement );
		o.argument.confirm();
	}
	function loadCategory(node, fnLoadComplete) {
		var request = YAHOO.util.Connect.asyncRequest('POST', request_uri, { success:loadCategorySuccessHandler,  argument:{ parent:node, confirm:fnLoadComplete } }, request_query+'categories&channel_id='+channel_id+'&sub_channel_id='+sub_channel_id+'&category_id='+node.data.id+'&old_category_id='+document.getElementById( category_prefix+'_id' ).value );
	}
	
	function loadAmazonMwsAttributes(category_id){
		if( category_id > 0 ) {
            // show progress
            bLoadingAttributes  = true;
            showLoadingIcon();
			var request = YAHOO.util.Connect.asyncRequest('POST', request_uri, { success:loadAmazonMwsAttributesSuccessHandler, failure: loadAmazonMwsAttributesFailureHandler }, request_query+'amazon_mws_attributes&item_id='+item_id+'&channel_id='+channel_id+'&sub_channel_id='+sub_channel_id+'&category_id='+category_id );
		} else {
			hidePanel();
		}	
	}
	
	function loadEbayAttributes( category_id ) {
		if( channel_id == 1 && typeof( ebay_attribtes ) != 'undefined' && ebay_attribtes == '1' && category_id > 0 ) {
            // show progress
            bLoadingAttributes  = true;
            showLoadingIcon();
            
			var request = YAHOO.util.Connect.asyncRequest('POST', request_uri, { success:loadEbayAttributesSuccessHandler, failure: loadEbayAttributesFailureHandler }, request_query+'ebay_attributes&channel_id='+channel_id+'&sub_channel_id='+sub_channel_id+'&category_id='+category_id+'&offer_type_id='+offer_type_id );
		} else {
			hidePanel();
		}
	}
	// this method loads attributes html when leaf is clicked
	function loadEbayAttributesSuccessHandler( o ) {
		return_data =  o.responseXML.documentElement;
		if( return_data.getElementsByTagName('html')[0].firstChild.data != '' ) {
			var script = document.createElement( "script" );
			script.setAttribute('type','text/javascript');
			script.text = return_data.getElementsByTagName('script')[0].firstChild.data;
			document.getElementById( category_prefix+'_attributes' ).innerHTML = return_data.getElementsByTagName('html')[0].firstChild.data;
			document.getElementsByTagName( 'body' )[0].appendChild( script );
		}
            
        // attrubites loaded
        bLoadingAttributes  = false;
        hideLoadingIcon();  
		
		hidePanel();
	}
	
    // this method loads attributes html when leaf is clicked
    function loadAmazonMwsAttributesFailureHandler( o ) {
            bLoadingAttributes = false;
            hideLoadingIcon();  
    }
    
	// this method loads attributes html when leaf is clicked
	function loadAmazonMwsAttributesSuccessHandler( o ) {
		return_data = o.responseXML.documentElement;
		if( return_data.getElementsByTagName('html')[0].firstChild.data != '' ) {
			var script = document.createElement( "script" );
			script.setAttribute('type','text/javascript');
			script.text = return_data.getElementsByTagName('script')[0].firstChild.data;
			document.getElementById( category_prefix+'_attributes' ).innerHTML = return_data.getElementsByTagName('html')[0].firstChild.data;
			document.getElementsByTagName( 'body' )[0].appendChild( script );
		}
            
        // attrubites loaded
        bLoadingAttributes  = false;
        hideLoadingIcon();  
		
		hidePanel();
	}
	
    // this method loads attributes html when leaf is clicked
    function loadEbayAttributesFailureHandler( o ) {
            bLoadingAttributes  = false;
            hideLoadingIcon();  
    }    
    
    
	function buildTree() {
		tree = new YAHOO.widget.TreeView( category_prefix+'_tree' );
		tree.setDynamicLoad( loadCategory, 1 );
		//tree.setExpandAnim(YAHOO.widget.TVAnim.FADE_IN);
		//tree.setCollapseAnim(YAHOO.widget.TVAnim.FADE_OUT);
		loadRootCategories();
	}
    function showPanel() {
        // picked hides manual selection errors
        hideErrors();
        panel.show();
    }
	function hidePanel() {
		panel.hide();
	}
	function buildPanel() {
		var attr = {
			close:true,
			visible:false,
			draggable:true,
			modal:true,
			constraintoviewport:true,
			fixedcenter:true,
			shadow:true
			//effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.2}
		};
		panel = new YAHOO.widget.Panel( category_prefix+'_panel', attr );
		panel.cfg.setProperty('width','500px');
		panel.render();
		// find category popup button
		YAHOO.util.Event.addListener( category_prefix+'_button', "click", showPanel, '', true);
		// refresh button
		YAHOO.util.Event.addListener( category_prefix+'_SelectById_button', "click", selectCategoryById, '', true);
	}
	
	// invoked when refresh category button is pressed
	function selectCategoryById(){
        hideErrors();
	    var field = document.getElementById( category_prefix+'_inputIdField');
	    var fieldInt = parseInt(field.value);
	    if( isNaN(fieldInt) || field.value.search(/[^0-9]/)>-1 ){
	        // its not a valid integer so lets just show an error
	        showDataError();
	    }else{
            document.getElementById( category_prefix+'_id' ).value = fieldInt;
            
            // show progress for both
            bLoadingName        = true;
            showLoadingIcon();
            if (channel_id == 1){
            	// call home to see if the id is ok and to get the full name - max 20s
            	var request = YAHOO.util.Connect.asyncRequest('POST', request_uri, 
            				{ success: selectCategoryByIdSuccess, failure: selectCategoryByIdFailure, timeout: 20000 }, 
                            	request_query+'ebay_category_by_id&channel_id='+channel_id+'&sub_channel_id='+sub_channel_id+'&category_id='+fieldInt 
                        	);
            }
            if (channel_id == 4){
            	// call home to see if the id is ok and to get the full name - max 20s
            	var request = YAHOO.util.Connect.asyncRequest('POST', request_uri, 
            				{ success: selectCategoryByIdSuccess, failure: selectCategoryByIdFailure, timeout: 20000 }, 
                            	request_query+'amazon_mws_category_by_id&channel_id='+channel_id+'&sub_channel_id='+sub_channel_id+'&category_id='+fieldInt 
                        	);
            }
	    }
    }
    // if we got some response
    function selectCategoryByIdSuccess( o ){
		// hide all error diva
		hideErrors();
		
		// if there is no xml show error
		if( !o.responseXML ){
            showConnectionError();
            return false;
		}
		
        // I dont like this data via XML but it was like that before so did not want to involve JSON to make it even more confusing
        var sResponseXML        = o.responseXML.documentElement;
        // get category id as int
        var eCategoryElement    = sResponseXML.getElementsByTagName('category_id')[0];
        var sCategoryId         = eCategoryElement.firstChild.data;
        var iCategoryId         = parseInt(sCategoryId);
        // get name string
        var eCategoryElement    = sResponseXML.getElementsByTagName('full_name')[0];
        var sCategoryFullName   = eCategoryElement.firstChild.data;
        if( isNaN(iCategoryId) || iCategoryId == 0 ){
            // hide progress 
            bLoadingName        = false;
            hideLoadingIcon();
            // show error div if id is incorrect
            showDataError();
        }else{
        	if (channel_id == 1){
        		loadEbayAttributes( iCategoryId );
        	}
        	if (channel_id == 4){
        		loadAmazonMwsAttributes( iCategoryId );
        	}
            document.getElementById( category_prefix+'_name' ).innerHTML = sCategoryFullName;
            // hide progress only for name
            bLoadingName        = false;
            hideLoadingIcon();
        }
    }
    // if we got some network error show the div
    function selectCategoryByIdFailure( o ){
        // hide progress 
        hideLoadingIcon();

        showConnectionError();
    }
    
    // methods showing errors    
    function hideErrors(){
        // hide errors
        var eDataErrorField = document.getElementById( category_prefix + '_data_error' );
        var eConnErrorField = document.getElementById( category_prefix + '_conn_error' );
        if( eDataErrorField ){
            eDataErrorField.style.display = 'none'; 
        }
        if( eConnErrorField ){
            eConnErrorField.style.display = 'none'; 
        }
    }
    function showConnectionError(){
        var eConnErrorField = document.getElementById( category_prefix + '_conn_error' );
        if( eConnErrorField ){
            eConnErrorField.style.display = ''; 
        }
    }
    function showDataError(){
        var eDataErrorField = document.getElementById( category_prefix + '_data_error' );
        if( eDataErrorField ){
            eDataErrorField.style.display = ''; 
        }
    }

    // when something is loading we can show/hide icon instead of text    
    function showLoadingIcon(){
        var fieldIcon = document.getElementById( category_prefix+'_loading');
        var fieldName = document.getElementById( category_prefix+'_name');
        if(fieldIcon && fieldName){
            // show only if there is something loading
            if( bLoadingName || bLoadingAttributes ){
                fieldIcon.style.display = '';
                fieldName.style.display = 'none';
            }
        }
    }
    function hideLoadingIcon(){
        var fieldIcon = document.getElementById( category_prefix+'_loading');
        var fieldName = document.getElementById( category_prefix+'_name');
        if(fieldIcon && fieldName){
            // hide only if all flags are switched off (finished loading everything)
            if( !bLoadingName && !bLoadingAttributes ){
                fieldIcon.style.display = 'none';
                fieldName.style.display = '';
            }
        }
    }
};