
// ############################################################################
// ######### NUMISMATIK JAVASCRIPT LIB                                #########
// ######### Copyright: SiteForce AG - 2008  Programming: fk@siteforce.de  ####
// ######### version: 18.02.2009 15:37 Uhr  						  #########
// ############################################################################


//#### condition mapping array for LED Display ######
var gCONDITION_MAPPING = new Array(
	{condition:'null', value:0},
	{condition:'durchschnittlich', value:3},
	{condition:'s', value:1},
	{condition:'s-ss', value:1},
	{condition:'f.ss', value:2},
	{condition:'ss', value:2},
	{condition:'ss+', value:3},
	{condition:'ss-vz', value:3},
	{condition:'f.vz', value:4},
	{condition:'vz', value:4},
	{condition:'vz+', value:4},
	{condition:'vz-st', value:5},
	{condition:'unz', value:5},
	{condition:'f.st', value:5},
	{condition:'st', value:6},
	{condition:'EA', value:6},
	{condition:'PP', value:6}
	);



// #### AJAX XML HTTP REQUEST CONSTANTS  #####
var xmlHttp = false;  				// ### AJAX global xmlhttprequest object
var REQUEST_GET = 0;
var REQUEST_POST = 2;
var REQUEST_HEAD = 1;
var REQUEST_XML = 3;



// ###################################################################################
// ####################################  AJAX Handler ################################
// ###################################################################################
 
 
 // ###########  processAJAXData  ###########
function processAJAXData(xmlHttp, intID ){
    //var data = xmlHttp.responseText;
    var data = xmlHttp.responseXML;
   
	if(data == null){return;} // ## start XML parsing onyl if responseXML data is existing

	//##### XML ATOM FORMAT FEED ROOT DATA    #####
	var feedRoot = data.getElementsByTagName('feed').item(0);
	var feedType = getXMLTagValue(feedRoot,'feedType');

    //alert("xmlHttp: " + xmlHttp + " , intID: " + intID + " feedType: " + feedType);
    //###### DATA PROCESSING SWITCH #######
    switch (feedType) {
    	case "product_browser":
    		processSmartBrowserColData(xmlHttp, intID); // ### render smart browser column 
    		break;
  		case "product_list":
  			alert("OLD product_list call");
    		//processProductListData(xmlHttp, intID); // ### render product list 
    		break;
  		case "product_data":
    		processProductData(xmlHttp, intID); // ### render product detail data 
  			break;
  		default:
			processData(xmlHttp, intID); // ### default process data 
    		break;
	}
    
}


// #############  getXMLRequester  - returns xmlhttprequest object or false  ##########
function getXMLRequester( ) {
    var xmlHttp = false;
            
    // try to create a new instance of the xmlhttprequest object        
    try {
        // Internet Explorer
        if( window.ActiveXObject ){
            for( var i = 5; i; i-- ) {
                try {
                    // loading of a newer version of msxml dll (msxml3 - msxml5) failed
                    // use fallback solution
                    // old style msxml version independent, deprecated
                    if( i == 2 ){
                        xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP" );    
                    }
                    // try to use the latest msxml dll
                    else {
                        xmlHttp = new ActiveXObject( "Msxml2.XMLHTTP." + i + ".0" );
                    }
                    break;
                }
                catch( excNotLoadable ) {                        
                    xmlHttp = false;
                }
            }
        }
        // Mozilla, Opera und Safari
        else if( window.XMLHttpRequest )
        {
            xmlHttp = new XMLHttpRequest();
        }
    }
    // loading of xmlhttp object failed
    catch( excNotLoadable ){
        xmlHttp = false;
    }
    
    return xmlHttp ;
}




/**
 * sends a http request to server
 *
 * @param strSource, String, datasource on server, e.g. data.php
 *
 * @param strData, String, data to send to server, optionally
 *
 * @param intType, Integer,request type, possible values: REQUEST_GET, REQUEST_POST, REQUEST_XML, REQUEST_HEAD default REQUEST_GET
 *
 * @param intID, Integer, ID of this request, will be given to registered event handler onreadystatechange', optionally
 *
 * @return String, request data or data source
 */
 
// ##########  sendAJAXRequest  #########
function sendAJAXRequest( strSource, strData, intType, intID ) {
    if( !strData )
        strData = '';

    // default type (0 = GET, 1 = xml, 2 = POST )
    if( isNaN( intType ) )
        intType = 0; // GET

    // previous request not finished yet, abort it before sending a new request
    if( xmlHttp && xmlHttp.readyState )
    {
        xmlHttp.abort( );
        xmlHttp = false;
    }
        
    // create a new instance of xmlhttprequest object
    // if it fails, return
    if( !xmlHttp )
    {
        xmlHttp = getXMLRequester( );
        if( !xmlHttp )
            return;
    }
    
    // parse query string
    if( intType != 1 && ( strData && strData.substr( 0, 1 ) == '&' || strData.substr( 0, 1 ) == '?' ) )
        strData = strData.substring( 1, strData.length );

    // data to send using POST
    var dataReturn = strData ? strData : strSource;
    
    switch( intType ) {
        case 1:    // xml
            strData = "xml=" + strData;
        case 2: // POST
            // open the connection 
            xmlHttp.open( "POST", strSource, true );
            xmlHttp.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
            xmlHttp.setRequestHeader( 'Content-length', strData.length );
            break;
        case 3: // HEAD
            // open the connection 
            xmlHttp.open( "HEAD", strSource, true );
            strData = null;
            break;
        default: // GET
            // open the connection 
            var strDataFile = strSource + (strData ? '?' + strData : '' );
            xmlHttp.open( "GET", strDataFile, true );
            strData = null;
    }
    
    // set onload data event-handler
    xmlHttp.onreadystatechange = new Function( "", "processAJAXResponse(" + intID + ")" ); ;

    // send request to server
    xmlHttp.send( strData );    // param = POST data
    
    return dataReturn;
}



// ##########  handleAJAXError - handle response errors   ###########
function handleAJAXError( xmlHttp, intID ){
    //alert("AJAX ERROR: " + xmlHttp + " ID: " + intID);
    //var messagString = "Online Connection AJAX ERROR: " + xmlHttp + " ID: " + intID;
    //var messageType = "ERROR"; 
    //message(messagString,messageType);
}


 // ################  processAJAXResponse  #################
function processAJAXResponse( intID ) {
    // status 0 UNINITIALIZED open() has not been called yet.
    // status 1 LOADING send() has not been called yet.
    // status 2 LOADED send() has been called, headers and status are available.
    // status 3 INTERACTIVE Downloading, responseText holds the partial data.
    // status 4 COMPLETED Finished with all operations.
    switch( xmlHttp.readyState ) {
        // uninitialized
        case 0:
        // loading
        case 1:
        // loaded
        case 2:
        // interactive
        case 3:
            break;
        // complete
        case 4:    
            // check http status
            if( xmlHttp.status == 200 )    // success
            {
                //processProductListData( xmlHttp, intID );
                processAJAXData( xmlHttp, intID );
            }
            // loading not successfull, e.g. page not available
            else
            {
                if( window.handleAJAXError )
                    handleAJAXError( xmlHttp, intID );
                else
                    alert( "ERROR\n HTTP status = " + xmlHttp.status + "\n" + xmlHttp.statusText ) ;
            }
    }
}
	

// ###############   createDOMElement    ###############
function createDOMElement(mElementType, mParentElement ,mTextString, mClassName , mElementID ){
		// ### this DOM implementation works form version IE 6 and newer ####
		var mNewObject = document.createElement(mElementType);			
 		var mClassObject = document.createAttribute("class");
		
		
 		if( mClassName  != ""){
 			mClassObject.nodeValue = mClassName ;
 			mNewObject.setAttributeNode(mClassObject);
 		}
 		
 		
 		if( mElementID  != "") {
 			//alert("mElementID " + mElementID );
 			var mIDObject = document.createAttribute("id");
 			mIDObject.nodeValue = mElementID ;
 			mNewObject.setAttributeNode(mIDObject);
 		}
 		
 
 		if(mTextString != "") { 
            if (mElementType.toLowerCase() == "div") {
                mNewObject.innerHTML = mTextString;
            } else {
				var mTextNode = document.createTextNode("" + mTextString);
				mNewObject.appendChild(mTextNode);
            }
		}

 		mParentElement.appendChild(mNewObject);

		return mNewObject;
};


// ###########   attachEventListener #############
function attachEventListener(target, eventType, functionRef, capture){
		// ## cross browser compatible attachEventListener function -- function can be called with a pointer or a string representing a function name
	
      	if (typeof(functionRef)== 'string') {
            functionRef=eval(functionRef);
      	}

  		if (typeof target.addEventListener != "undefined"){
    		target.addEventListener(eventType, functionRef, capture);
		} else if (typeof target.attachEvent != "undefined"){
			target.attachEvent("on" + eventType, functionRef);
  		} else {
    		eventType = "on" + eventType;
		
    	if(typeof target[eventType] == "function"){
        	var oldListener = target[eventType];
        	target[eventType] = function(){
            	oldListener();
            	return functionRef();
        	};
    	} else {
        	target[eventType] = functionRef;
    	}
  	}
}



// ###################################################################################
// ##################          SiteForce HELPER FUNCTIONS          ###################
// ###################################################################################

// #############  updateConditionIndicator  ##########
function updateConditionIndicator(elementID,checkConditionString) {

	//alert("updateConditionIndicator: " + elementID + " " + checkConditionString);
	var productConditionValue = getCondicitonValue(checkConditionString)

 	// ####### Update condition LED indicator  ####### 
	var productConditionIndicatorElement = document.getElementById(elementID);
	if(productConditionIndicatorElement != null){
		productConditionIndicatorElement.innerHTML = "";
		var verticalOffset = (productConditionValue * 10);
		productConditionIndicatorElement.style.backgroundPosition = '0px -' + verticalOffset + 'px'; // ### shift vertical offset of bgnd image
	}
}

//#########  ShowObjectProperties  #############
function ShowObjectProperties(mObject) {
	var mWindow = window.open("", "DEBUG", "toolbar=0,location=0,directories=0,scrollbars=1,status=0,menubar=1,resizable=1,width=500,height=600");
	mWindow.document.open();

	for (var i in mObject) {
		mWindow.document.write('<BR><B>' + i + '</B> = ' + mObject[i] );
	}

	mWindow.document.close();
	mWindow.focus();
}


//#########  getBrowser  #############
function getBrowser() {
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1) return 'Opera';
	if (agt.indexOf("staroffice") != -1) return 'Star Office';
	if (agt.indexOf("webtv") != -1) return 'WebTV';
	if (agt.indexOf("beonex") != -1) return 'Beonex';
	if (agt.indexOf("chimera") != -1) return 'Chimera';
	if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	if (agt.indexOf("firefox") != -1) return 'Firefox';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	if (agt.indexOf("msie") != -1) return 'Internet Explorer';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	if (agt.indexOf('\/') != -1) {
	if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
		return navigator.userAgent.substr(0,agt.indexOf('\/'));}
		else return 'Netscape';} else if (agt.indexOf(' ') != -1)
		return navigator.userAgent.substr(0,agt.indexOf(' '));
	else return navigator.userAgent;
}



// ###########  getXMLTagValue  ###########
function getXMLTagValue(mDomObject, mTagName ){
	var mReturnValue = ""; 
	if(mDomObject != null) {
		// mDomObject.getElementsByTagName('title').item(0).firstChild.nodeValue ;
		var mChildList = mDomObject.getElementsByTagName(mTagName);
		if(mChildList.length > 0){
			if(mChildList[0].firstChild != null){
				var mFirstChildNodeValue = mChildList[0].firstChild.nodeValue;
			}
			if(mFirstChildNodeValue != null){ mReturnValue = mFirstChildNodeValue; }		
		}
	}
	return mReturnValue;
}


// ###########  getXMLTagAttribute  ###########
function getXMLTagAttribute(mDomObject, mTagName, mAttributeName ){
	var returnValue = ""; 
	if(mDomObject != null) {
		var mChildList = mDomObject.getElementsByTagName(mTagName);
		if(mChildList.length > 0){
			if(mChildList[0] != null){
				//ShowObjectProperties(mChildList[0]);
				var attributeValue = mChildList[0].getAttribute(mAttributeName);;
			}
			if(attributeValue != null){ returnValue = attributeValue; }		
		}
	}

	return returnValue;
}



// ###############   fadeElementIn    ###############
function fadeElementIn(elementId,steps,startDelay){
	if(steps == null){var steps = 10;}
	if(startDelay == null) {var startDelay = 0;} // ### start delay in milliseconds, 0 = no delay, 1000 = 1 second delay
	//alert("fadeIn: " + elementObject + " steps: " + steps + " startDelay: " + startDelay);
	for(var n = 0; n <= steps; n++){
		var delay = (n * 50) + startDelay;
		var opacity = (1.0 / steps) * n;
		setTimeout("setElementOpacity('" + elementId + "'," + opacity +")", delay);
	}
}


// ###############   setElementOpacity    ###############
function setElementOpacity(elementId, opacity){
		
	var elementObject = document.getElementById(elementId);
	
	alert("setElementOpacity " + elementId + " elementObject: " + elementObject);
	
	if(elementObject != null) {
		elementObject.style.opacity = opacity;
		//elementObject.style.filter = "alpha(opacity=" + (opacity * 100.0) +")";
	}
}
  

// ###############   setEveryOpacity    ###############
function setEveryOpacity(elementIdList){
	for(var n = 0; n < elementIdList.length; n++){
		var elementId = elementIdList[n];
		var element = document.getElementById(elementId);
		if(element != null) {
			element.style.opacity = opacity;
			element.style.filter = "alpha(opacity=" + (opacity * 100.0) +")";
		}
	}
}



// ###############   displayElement    ###############
function displayElement(id, status){
	if(status == null){var status = true;}
	
	var element = document.getElementById(id);
	if(element != null) {
		if(status == false){
			element.style.display = "none";
			element.style.visibility = "hidden";
		}
		
		if(status == true){
			element.style.display = "inline";
			element.style.visibility = "visible";
		}
	}
}

// ### setInnerHtml  ###
function setInnerHtml(elementId, innerHtmlText) {
	var element = document.getElementById(elementId);
	if(element != null) {
		element.innerHTML = "" + innerHtmlText;
	}
}
	
// ### visibilityElement  ###
function visibilityElement(elementId, status) {
	var element = document.getElementById(elementId);
	if(element != null) {
		if(status == true){
			element.style.visibility = "visible";
		} else {
			element.style.visibility = "hidden";
		}
	}
}
		

	
// ###########   getFileName #############
function getFileName(mURL) {	
	var fileStr = mURL.replace(/url\(/, "");  // ## replace url( with nothing
	var fileStr = fileStr.replace(/\)/, "");  // ## replace ) with nothing
	
	var pathChunks = fileStr.split("/");
	var file = fileStr;
	if(pathChunks.length > 0){
		var file = pathChunks[pathChunks.length - 1];
	}  			
	
	return file;
}
	
	
// ###########   loadingIndicator #############
function loadingIndicator(mStatus) {
	var modalLoadingAreaElement = document.getElementById('modalLoadingArea'); // ### modalLoadingArea Element	
	var magnifyImageElement = document.getElementById('magnifyImage'); // ### actual displayed image Element
				
	if (modalLoadingAreaElement != null){
		if(mStatus == true){
			// ### hide highres image ####
			if (magnifyImageElement != null){	
				magnifyImageElement.style.visibility = 'hidden';
			}
			modalLoadingAreaElement.style.visibility = 'visible';
			modalLoadingAreaElement.style.display = 'block';
		} else {
			modalLoadingAreaElement.style.visibility = 'hidden';
			modalLoadingAreaElement.style.display = 'none';
			
			// ### show highres image ####
			if (magnifyImageElement != null){	
				magnifyImageElement.style.visibility = 'visible';
			}
		}
	}
}

// ###############   setProgressIndicator    ###############
function setProgressIndicator( elementId, status, style) {
	var progressIDElement = document.getElementById(elementId);	
	if(style == null){var style = "";}
	
	//alert("progressIDElement: " + progressIDElement + " status:" + status);
	if(progressIDElement != null){
		if(status == null) {var status = "on";}
		if(status == "on"){ var className = "loadIndicatorActive" + style; }
		if(status == "off"){ var className = "loadIndicator"; }
		if(progressIDElement.className != className) { progressIDElement.className = className; }
	}
}


// ###############   message    ###############
function message( messagString,messageType) {
	var messageElement = document.getElementById('messageDisplay');	
	if(typeof(messageType) == "undefined") {messageType = "ERROR";} 
	if(typeof(messagString) == "undefined") {messagString = "Default Message";} 
	
	if(messageElement != null){
		messageElement.innerHTML = messagString;
	}
}

    

// ###############   getCondicitonValue    ###############
function getCondicitonValue(checkConditionString) {
	var dataExisting = false;
	
	for(i=0; i< gCONDITION_MAPPING.length; i++){
		// ### syntax name,count,parentId,id
		var mObject = gCONDITION_MAPPING[i] ;	
		var conditionString = mObject.condition;
		var conditionValue = mObject.value;
	
		if(conditionString == checkConditionString) {
			var dataExisting = true;
			return conditionValue;
			break;
		}
	}
	
	return 0;
}	


// ###############   getQueryStringArgumentsArray    ###############
function getQueryStringArgumentsArray() {
	var args = new Object();
	var query = location.search.substring(1);
	var pairs = query.split("&");
	for(var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');
		if (pos == -1) continue;
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
	}
	
	return args; 
}


