 /* Utility functions */



 ////                                                              //
 //                                                                //
 ////******************  FORM ELEMENTS  *************************////
 //                                                                //
 ////                                                              //


 ////  Removes all options from a given SELECT element, leaving only the first one selected
 //
 function select_clear(select_id)
 {
     var select_element = $(select_id);

     if (select_element == null || select_element.tagName != 'SELECT')
     {
         return false;
     }
     select_element.disable();

     while (select_element.length > 1)
     {
         select_element.options[1] = null;
     }
     select_element.options[0].selected = true;
     select_element.enable();
 }


 ////  Adds the OPTIONs to the supplied SELECT, taken from an array of objects
 //
 //    Objects in the array are supposed to have a "value" and a "name" property
 //
 function select_build(select_id, item_array)
 {
     var select_element = $(select_id);

     if (select_element == null || select_element.tagName != 'SELECT')
     {
         return false;
     }

     var orig_size = select_element.length;
     var limit     = item_array.size();
     for (var i=0; i<limit; i++)
     {
//         select_element.options[orig_size+i] = new Option(item_array[i].name, item_array[i].value);
         select_element.options[orig_size+i] = new Option(repair_string(item_array[i].name), item_array[i].value);
     }

 }



 ////  Selects a specific option in a given select. Selection on option value.
 //
 function select_choose(select_id, value_to_select)
 {
     var select_element = $(select_id);

     if (select_element == null || select_element.tagName != 'SELECT')
     {
         return false;
     }

     var optionsLength = select_element.options.length;
     var i;

     for (i=0; i<optionsLength; i++)
     {
         if (select_element.options[i].value == value_to_select)
         {
             select_element.options[i].selected = true;
         }
     }
 }



 ////                                                              //
 //                                                                //
 ////******************  XML  PARSISNG  *************************////
 //                                                                //
 ////                                                              //

 ////  Create and return the cross-browser XML document object from a text string
 //
 function xml_load(text)
 {
     ////  Load the XML data from string
     //
     var _result;

     // code for IE
     if (window.ActiveXObject)
     {
         var _result = new ActiveXObject('Microsoft.XMLDOM');

         _result.async = 'false';
         _result.loadXML(text);
     }
     // code for Mozilla, Firefox, Opera, etc.
     else
     {
         var parser  = new DOMParser();
         var _result = parser.parseFromString(text, 'text/xml');
     }

     _result = _result.documentElement;

     return _result;
 }


 function date_get_from_value (date, hour, min)
 {

     var reg =  /^([0-9]{1,2})[\.\,]([0-9]{1,2})[\.\,]([0-9]{2}|[0-9]{4})$/;

     if(reg.exec(date))
     {
             var datArr  =  reg.exec(date);
             datArr[3]   =  (datArr[3].length == 2)? '20' + datArr[3] : datArr[3];
             datArr[2]   =  (datArr[2] > 0 )? datArr[2] - 1 : 11;
             actDate     =  new Date(datArr[3], datArr[2], datArr[1], hour, min, 0);

             return actDate.getTime();
     }
     else
     {
         return false;
     }
 }


 function object_to_form_submit(object, form, clear)
 {
     var f = $(form);

     if (clear)
     {
         inputs = f.getElementsByTagName('INPUT');

         for (var i=inputs.length-1; i>=0; i--)
         {
             f.removeChild(inputs[i]);
         }
     }

     for (param in object)
     {
         var tmp = document.createElement('INPUT');

         tmp.setAttribute("type", "hidden");
         tmp.setAttribute("name", param);
         tmp.setAttribute("value", eval('object.'+param));

         f.appendChild(tmp);
     }

     f.submit();
 }


 function object_to_request_string(object)
 {
     var property;
     var delimiter = '';
     var result    = '';

     for(property in object)
     {
         result += delimiter + property +'='+escape(eval('object.'+property));

     delimiter='&';
     }

     return result;
 }


 function object_to_string(object)
 {
     var result = '';

     for (var property in object)
         result += property + ":\t\t"+eval('object.'+property) + "\n";

     return result;
 }


 function get_nextsibling(n)
 {
     var x=n.nextSibling;
     
     while (x.nodeType!=1)
     {
         x = x.nextSibling;
     }

     return x;
 }


 function stripSpaces(element)
 {
     textIn = element.value;
     textOut = '';

     for (i=0;i<textIn.length;i++)
     {
         c = textIn.charAt(i);

         if(c != ' ')  textOut += c;
     }
     element.value=textOut;
 }

 function check_mail(mail_string)
 {
     var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var regex = new RegExp(emailReg);

     return regex.test(mail_string);
 }
 

 function logos_layer_open_ts(https)
 {
     if (typeof(https) == 'undefined')
         openLayer2('Sicherheit', '...', 'http://www.m-broker.de/sicherheit_ts/', '', '418', '253');     
     else
         openLayer2('Sicherheit', '...', 'proxy.jsp?uri=/sicherheit_ts/', '', '418', '253');     
 }
 
 function logos_layer_open_tuv(https)
 {
     if (typeof(https) == 'undefined')
         openLayer2('Sicherheit', '...', 'http://www.m-broker.de/sicherheit_tuv/', '', '418', '253');     
     else
         openLayer2('Sicherheit', '...', 'proxy.jsp?uri=/sicherheit_tuv/', '', '418', '253');     
 }
 function logos_layer_open_verisign(https)
 {
     if (typeof(https) == 'undefined')
         openLayer2('Sicherheit', '...', 'http://www.m-broker.de/sicherheit_verisign/', '', '418', '253');     
     else
         openLayer2('Sicherheit', '...', 'proxy.jsp?uri=/sicherheit_verisign/', '', '418', '263');     
 }
 



 var popupWindow;
 function openWindow(url, sizex, sizey)
 {
     popupWindow = window.open (url, "popupWindow", "location=0,status=0,scrollbars=1,width="+sizex+",height="+sizey);
 }
 
 
 
 function fixPng(img)
 {
     if(document.all)
     {
         img.parentNode.style.width  = img.offsetWidth;
         img.parentNode.style.height = img.offsetHeight;
         img.parentNode.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale src='"+ img.src +"')";
     } 
     else 
     {
         img.style.visibility = "visible";
     }
 }
 
 
 function check_errors(type)
 {
    var error_flag = false;
		        
    if (typeof(error_msg) != 'undefined' && error_msg) 
    {
        alert(error_msg);
        error_msg = '';
        error_flag = true;
    }
											           
    if (typeof(type) == 'undefined' && typeof(success_msg) != 'undefined' && success_msg)
    {
        alert(success_msg);
	success_msg = '';
        error_flag = true;
    }
															           
    if (typeof(business_msg) != 'undefined' && business_msg)
    {
        alert(business_msg);
        business_msg = '';
        error_flag = true;
    }
    return error_flag;
 }  
 
 
 
function printContent(id)
{
	if (document.getElementById != null)
	{
		if (typeof(id) == 'undefined' || id == null)
			id = 'printReady';

		if (!document.getElementById(id))
        {
            alert('Could not find the "print" section in HTML');
			return;
		}

		var html = "<HTML>\n<HEAD>\n";

		if (document.getElementsByTagName != null)
		{
			var headTags = document.getElementsByTagName("head");
			if (headTags.length > 0)
				html += headTags[0].innerHTML;
		}

		html += "\n</HEAD>\n<BODY id='section-print'>\n";

		var printElem = document.getElementById(id);
		var myregexp  = new RegExp("<script[^>]*?>.*?<\\/script>", "ig");

    	result = printElem.innerHTML.replace(myregexp, '');
		html  += result;


		html += "\n</BODY>\n</HTML>";


		var printWin = window.open("","print");
		printWin.document.open();
		printWin.document.write(html);
		printWin.document.close();

		printWin.print();
	}
	else
	{
		alert("Sorry, the print feature is only available in modern browsers.");
	}
}

 function format_price(price)
 {
     price += '';
   
     var fraction = '';
     var full     = '';
     
     if (price.indexOf(".") != -1)
     {     
         fraction += price.substr(price.indexOf(".") + 1);
         full     += price.substr(0, price.indexOf("."));
     }
     else
     {
         fraction += '00';
         full     += price;
     }     

	     
     var new_full = '';
     if (full.length > 3)
     {
         var stop = full.length - 3;
				          
         new_full = full.substr(0, stop) + '.' + full.substr(stop);    
     }
     else
     {
         new_full = full;
     }
	
     if (fraction.length == 1)
         fraction += '0';

     var result_price = new_full + ',' + ('' + fraction).substr(0, 2);
     
     return result_price;
 }

 function debug(text)
 {
     var div = $('debug');
     
     if (typeof(div) != 'undefined')
     {
         div.innerHTML += text + "<br />";
     }
 }
 
 
   function get_rrs_price()
  {
  
      var fromDate = new Date();
      var toDate   = new Date();
      var days;
      var weeks;
  
      fromDate.setFullYear(_main_params.carFromDate.substr(6,4),  _main_params.carFromDate.substr(3,2) -1 , _main_params.carFromDate.substr(0,2));
      fromDate.setHours(_main_params.carFromHour);
      fromDate.setMinutes(_main_params.carFromMinute);
      fromDate.setSeconds(0);
  
  
      toDate.setFullYear(_main_params.carToDate.substr(6,4),  _main_params.carToDate.substr(3,2) -1 , _main_params.carToDate.substr(0,2));
      toDate.setHours(_main_params.carToHour);
      toDate.setMinutes(_main_params.carToMinute);
      toDate.setSeconds(0);
   
      days = parseInt((toDate - fromDate) / (1000*60*60*24)); // a week in microseconds
  
      weeks = Math.ceil(days / 7);
      
      return weeks*4.5;
  }




/**
 * Restores iso-8859-1 broken encodings into utf8
 * @param <string> suspicious_string
 * @return <string>
 */
function repair_string(suspicious_string)
{
	suspicious_string = '' + suspicious_string;

    // Broken Chars Mapping
    // RegExp non-safe chars should be escaped with \\
    // e.g. \\? \\+
    var charReflector = {};
    var codes = brokenChars();
    for(i in codes)
    {
        charReflector[codes[i]] = i;
    }

    var pattern = '';
    var delim = '';
    // Collecting RegExp with groups
    for( brokenChar in charReflector )
    {
        pattern += delim + '(' + brokenChar + ')';
        delim = '|';
    }

    var patternExpr = new RegExp(pattern, 'g');

    return suspicious_string.replace(patternExpr, function (slicedTxt, pTxt, patternedTxt)
    {
        return String.fromCharCode(charReflector[slicedTxt]);
    }
    )
}

/**
 * Prepares broken table
 */
function brokenChars()
{
    return  {
        214 : String.fromCharCode(195)+'\\?',
        246 : String.fromCharCode(195)+ String.fromCharCode(182),
        252 : String.fromCharCode(195)+ String.fromCharCode(188),
        180 : String.fromCharCode(194)+ String.fromCharCode(180),
        228 : String.fromCharCode(195)+ String.fromCharCode(164)
//		229 : String.fromCharCode(195)+ String.fromCharCode(63)
    };
}

