
var alreadyAdded = false;


/*
    Disclaimer

    While we make every effort to ensure that this code is fit for its intended purpose, we
    make no guarantees as to its functionality. CoreTrek AS will accept no
    responsibility for the loss of data or any other damage or financial loss caused by use
    of this code.


    Copyright

    This programming code is copyright of CoreTrek AS. Permission to run this code is given to
    approved users of CoreTrek's publishing system CorePublish.

    This source code may not be copied, modified or otherwise repurposed for use by a third
    party without the written permission of CoreTrek AS.

    Contact webmaster@coretrek.com for information.
*/

/*
 * Get the absolute position of a given element
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function getAbsolutePos(el){
    for (var lx=0,ly=0;el!=null;
    lx+=el.offsetLeft,ly+=el.offsetTop,el=el.offsetParent);
    return {x:lx,y:ly}
}

/*
 * Set the layer with the given id to
 * display:block.
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function displayLayer(layerId) {
    if(typeof $(layerId) != "undefined") {
        $(layerId).style.display = 'block';
    }
}

/*
 * Set the layer with a given id to
 * display:inline, position:absolute
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function hoverLayer(layerId) {
    if(typeof $(layerId) != "undefined") {
        $(layerId).style.display = 'inline';
        $(layerId).style.position = 'absolute';
    }
}

/*
 * Set a layer to display:none
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function hideLayer(layerId) {
    if(typeof $(layerId) != "undefined") {
        $(layerId).style.display = 'none';
    }
}

/*
 * Delegate function used by the hovermenu to hide
 * all hovering layers.
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
var hideAllHovermenuItems = function(id) {
    hovermenus = $('hovermenu-' + id).getElementsByClassName('hovermenuitem');
    for(i=0;i<hovermenus.length;i++) {
       hovermenus[i].style.display = 'none';
    }
}

/*
 * Function to get the mouse position from event
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function getMousePosition(event) {
    var pos;
    
    if (!event) var event = window.event;
	if (event.pageX || event.pageY) 	{
		posx = event.pageX;
		posy = event.pageY;
	}
    else if (event.clientX || event.clientY) 	{
		posx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}
	
	return {x:posx,y:posy};
}

/*
 * Display a hovering popup layer.
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 *
 * Layer will be absolute positioned and positioned
 * according to options. Default is to display the
 * popup with a small right offset to the mouse pointer.
 *
 * Options has to be of type Object, and the following
 * assosiated attributes can be used to configure popup:
 *   - x, override the x offset
 *   - y, override the y offset
 *   - fixedPosition, layer will be positioned at the fixed x/y position
 */
function popupLayerEvent(event, layerId, options) {
    if($(layerId) != null) {
        pos = getMousePosition(event);
        
        if(typeof options == "undefined") {
            var options = new Object();
        }
        
        var offsetY = 18;
        var offsetX = 14;
        if(typeof options['x'] != "undefined") {
            offsetX = options['x'];
        }
        
        if(typeof options['y'] != "undefined") {
            offsetY = options['y'];
        }
        
        var element = $(layerId);
        
        element.style.display = 'block';
        element.style.position = 'absolute';
                
        if(typeof options['fixedPosition'] == "undefined" || options['fixedPosition'] == false) {
            element.style.left = pos['x'] + offsetX + 'px';
            element.style.top = pos['y'] + offsetY + 'px';
        }
    }
}



function hideTooltipForReal(id) {
    //$(id).setStyle({
    //    display: 'none'
    //});
    $(id).hide();
}


function hideElementWithEffect(element) {
    Effect.Fade($(element).identify(),{delay:1});    
}

function showElementWithEffect(element) {
    Effect.Appear($(element).identify());    
}



/*
Google maps directions
*/

function setInactive() {
    var arrayOfLinks = $$('a.ml');
    arrayOfLinks.each(function(item) {
        item.removeClassName('active');
    });
}

function setActiveAddress(address, header) {
    $('toAddress').value = address;    
    $('route_container').show();
    $('route_header').update('KJØRERUTE TIL AVD. ' + header.toUpperCase());
    //$('route_header').setStyle({backgroundImage:'url(\'/header.php?size=12&color=gray&bg=white&type=l&text=KJØRERUTE TIL RØHNESELMER ' + header.toUpperCase() +'\')'}); // Viktig med kun &!
    $('route_header').setStyle({backgroundImage:'url(\'/header.php?size=12&color=gray&bg=white&type=l&text=KJØRERUTE TIL AVD. ' + header.toUpperCase() +'\')'}); // Viktig med kun &!
}

function setDirections(fromAddress, toAddress, locale) {
    gdir.load("from: " + fromAddress + " Norway " + " to: " + toAddress + " Norway",
    { "locale": locale });    
}

DealerLocator = Class.create(
{
	selectedDealer: null,
	selectedBusinessHoursElement: null,
	blnShowOverview: null,
	headerGeneratorUrl: null,
	selectedDealerName: null,
	foo : null,
	hsh : null,
	
	initialize: function() 	{
		this.blnShowOverview = true;
		this.selectedDealer = -1;
		this.hsh = new Hash();
	}, 
	
	prepareDirections: function() {
		$('locate_overview').hide();
		$('locate_dealer_' + this.selectedDealer).hide();
		$('route_container').hide();		
		$('directionsWrapper').show();
		// substitute heading
		$('locate_heading').style.backgroundImage = 'url(' + this.headerGeneratorUrl + "?size=16&color=gray&bg=white&type=l&text=KJØRERUTE+TIL+AVD.+" + this.selectedDealerName + '+)';
		$('locate_heading').update("KJØRERUTE TIL AVD. " + this.selectedDealerName);
	},
	
	reloadInfopage: function() {
		$('directionsWrapper').hide();		
		$('locate_dealer_' + this.selectedDealer).show();
		$('route_container').show();		
		// substitute heading
		$('locate_heading').style.backgroundImage = 'url(' + this.headerGeneratorUrl + "?size=16&color=gray&bg=white&type=l&text=RØHNESELMER+" + this.selectedDealerName + '+)';
		$('locate_heading').update("RØHNESELMER " + this.selectedDealerName);
	},
	
	setHeaderGeneratorUrl: function(url) {
		this.headerGeneratorUrl = url;
		// ?size=18&color=gray&bg=white&text=".$header;
	},
	
	dilldall: function() {
		alert("dealer id = " + this.selectedDealer);
	},
	
	showBusinesshours: function(id) {
		if (id != this.selectedBusinessHoursElement) {
			// hide current
			$('dealer' + this.selectedDealer + 'sub' + this.selectedBusinessHoursElement).hide();
			// show selected
			$('dealer' + this.selectedDealer + 'sub' + id).show();
			
			// update border-bottom on tabs
			$('dealer' + this.selectedDealer + 'tab' + this.selectedBusinessHoursElement).removeClassName('selected');
			$('dealer' + this.selectedDealer + 'tab' + id).addClassName('selected');
			this.selectedBusinessHoursElement = id;
		}
	},
	
	showOverview: function() {
		// substitute heading
		$('locate_heading').style.backgroundImage = 'url(' + this.headerGeneratorUrl + "?size=16&color=gray&bg=white&type=l&text=HER+FINNER+DU+OSS+)";

		// hide current
		$('locate_dealer_' + this.selectedDealer).hide();
		// show overview
		$('locate_overview').show();
		$('route_container').hide();
		this.blnShowOverview = true;
	},
	
	selectDealer: function(id, street, city, name) {
		// keep name for later use (graphics heading in directions)
		this.selectedDealerName = name.toUpperCase();
		
		// defined in googlemaps.js
		panToMarker(id);
		// defined in javascript.js
		setActiveAddress(street + " " + city, name);
		// defined in javascript.js
		setInactive();
		
		$('ml' + id).addClassName('active');

		// substitute heading
		$('locate_heading').style.backgroundImage = 'url(' + this.headerGeneratorUrl + "?size=16&color=gray&bg=white&type=l&text=RØHNESELMER+" + name.toUpperCase() + '+)';
		$('locate_heading').update("RØHNESELMER " + name.toUpperCase());
			
		// hide overview
		if (this.blnShowOverview) {
			$('locate_overview').hide();
			this.blnShowOverview = false;
		}
		// hide previous div
		if (this.selectedDealer != -1 && this.selectedDealer != id) {
			$('locate_dealer_' + this.selectedDealer).hide();
		}

		// show the first businesshours tab, update tab layout
		$('dealer' + id + 'sub1').show();
		$('dealer' + id + 'tab1').addClassName('selected');
		
		// hide the rest, update tab layout
		$('dealer' + id + 'sub2').hide();
		$('dealer' + id + 'tab2').removeClassName('selected');
		$('dealer' + id + 'sub3').hide();
		$('dealer' + id + 'tab3').removeClassName('selected');
		this.selectedBusinessHoursElement = 1;
		
		// update correct content div
		$('locate_dealer_' + id).show();
		this.selectedDealer = id;
	}
});

var dealerLocator;

/*
	printLightbox
	parameters:
		lightboxID: the ID of the content we want to print
		hideIDs: IDs to be hidden from the printout, comma separated
*/
function printLightbox(lightboxID, hideIDs) {
	/*
	requirements:
	1) the following divs must be defined just after body-level
		<div id="lb-print-hidden"></div>
		<div id="lb-print-interact"></div>
		<div id="lb-print-dest"></div>
	2) the following css must be present in style-print.css
		#lb-print-hidden,
		#lb-print-interact {
			display: none;
		}
	*/

	var arrHide = hideIDs.split(",");
	var randomTempID = "lks123jh1241f13513g6l5a7k5shf8648l4k5as7h357fl52k2a626s4jh6f";

	// clear lb-hide-print
	$('lb-print-hidden').update("");

	// place marker above wanted ID
	$(lightboxID).insert({before: "<div id='"+ lightboxID + randomTempID +"'></div>"});
	// move wanted ID to printable area
	$('lb-print-dest').update($(lightboxID));

	// place markers above each hideID
	// move all hideIDs to a hidden div
	for(var i=0; i<arrHide.length; i++) {
		$(arrHide[i]).insert({before: "<div id='" + arrHide[i] + randomTempID + "'></div>"});
		$('lb-print-hidden').insert($(arrHide[i]));
	}

	$('lb-print-interact').update("<br /><button onclick=\"restorePrintLightbox('"+lightboxID+"', '"+hideIDs+"', '"+randomTempID+"');\" >Tilbake</button>");

	// print
	window.print();
}

/*
	restorePrintLightbox
	used internally by printLightbox
*/
function restorePrintLightbox(lightboxID, hideIDs, randomTempID) {
	var arrHide = hideIDs.split(",");
	for(var i=0; i<arrHide.length; i++) {
		$(arrHide[i] + randomTempID).insert({after: $(arrHide[i])});
		$(arrHide[i] + randomTempID).remove();
	}

	// move wanted ID to marker
	$(lightboxID + randomTempID).insert({after: $(lightboxID)});
	// remove marker
	$(lightboxID + randomTempID).remove();

	// clear the interact div		
	$('lb-print-interact').update("");

	// all is well
}

/* Open lightbox with JS (used in Flash) */

function openLightBox(lb) {    
    if(lb == 'test_drive') {    
       //alert(testDriveUrl);
       //lightbox.show(testDriveUrl);
       openNewLightbox(testDriveUrl, true);
       
    } else {
        parameters = lb.split(';');
        if(parameters[0] == 'build') {
            
           	params = 'service=buildcar&model='+parameters[1];                
            //alert(params);    
           	new Ajax.Request('/xmlhttprequest.php', {
                parameters: params,
                method:'get',
                onSuccess: function(transport){
                    var response = transport.responseText || "no response text";
                    var options = 'width=792,height=700,menubar=no,toolbar=no,resizable=yes,location=no,scrollbars=yes';

                    window.open(response, 'buildcar', options);
                    
                    //lightbox.show(response);          
                    //redir(response);                    
                },
                onFailure: function(transport){ 
                    alert("En feil oppstod: "+transport.status);            
                }
            });
            
        }
    }   

}

function openProspectPage(parameters) {
    parametersArray = parameters.split(';');
    model = parametersArray[0];
    chassi = parametersArray[1];
    state = parametersArray[2];    
    
    params = 'service=usedcar&modelname='+model+'&chassis='+chassi+'&carstate='+state;
    // Variable initialized in head.php
    if(dealerCat) {
        params = params + "&catId="+dealerCat;
    }
           
    new Ajax.Request('/xmlhttprequest.php', {
        parameters: params,
        method:'get',
        onSuccess: function(transport){
            var response = transport.responseText || "no response text";
            //alert(response);            
            redir(response);            
        },
        onFailure: function(transport){ 
            alert("En feil oppstod: "+transport.status);            
        }
    });    
    
    
    //alert('Vis bruktbil, '+path);

}

function redir(url) {
    window.location = url;
    return false;    
}


/* Send customer service form */
function ajaxThis(formId) {
    new Ajax.Request('/xmlhttprequest.php', {
        parameters: $(formId).serialize(true),
        method:'get',
        onSuccess: function(transport){
            var response = transport.responseText || "No response text";
            
            clearRedErrorIndication(); 
            $('status').show();
            
            var responseCodes = response.split(',');

            //alert(responseCodes.first());
            //alert(response);
            
            if(responseCodes.first() == "ERR") {
                
                responseCodes.each(function(item) {
                    if(item != "ERR" && item != "") {
                        $(item).addClassName('rederror');
                        //alert(item);
                    }
                });
               
                //$('status').update(response);
            
            } else if (responseCodes.first()=="ERRSEND") {
                $('status').update("Sending feilet");
                
            } else {
                // Vis kvittering
                $('formContainer').hide(); 
                $('receipt').update(response);                   
                $('receiptContainer').show();
                
                if($('submitbutton') && $('submitbuttongrey')){
                   $('submitbutton').hide();   
                   $('submitbuttongrey').show();   
                }
            }   

            
            //$('status').update(response);
        },
        onFailure: function(transport){ 
            //alert(transport.status);
            $('status').show();
            $('status').update("Sending av skjema feilet! " + transport.status);
        }
        });
}

function clearRedErrorIndication() {
    $$('.zero').each(function(item) {
        item.removeClassName('rederror');
    });    
}


/* Remove default value for input type text and textareas */

function clearTextField(field,defaultText) {
		if (field.value == defaultText) {
			field.value = "";
		}    
}

function changeDate(date,customid) {
    data = date.split("-",3);
    var date2;
    date2 = data[2] + '.' + data[1] + '.' + data[0];
    
    if(customid) {
        $(customid).setValue(date2);

    } else {        
        $('date').setValue(date2);        
    }
    selectedDate = date2;
}

function setSelected(selectedElement) {
    if($(selectedElement)) {
        var sel = $$('table.calendar-layout a.selected');
        
        sel.each(function(item) {
            item.removeClassName('selected');
        });
        $(selectedElement).addClassName('selected');
    } else {
        //alert("No element");
    }

}


function setAvailableDate() {
    var date;
    date = availableDates.get($('department').getValue());

	// In case no department is selected
	/*if (typeof(date) == "undefined" || typeof(date) == null) {
		return;
	}*/ 	
	//alert(date);
	
	var date2;
	
	if(date == false) {
	    $('date').setValue("");	    	    
        
        $('prev_button').hide();
        $('next_button').hide();

	    var na = $$('#lb_service #cal td.na');
	    na.each(function(item) {
	        item.removeClassName('na');
	    });

	    var replacements = $$('#lb_service #cal td span.replacement');
	    replacements.each(function(item) {
	        item.hide();
	    });

	    for(i=1;i<=31;i++) {
	        if($('c'+i)) {
	            if(i < 32) {
	                $('c'+i).addClassName('na');	                
	            }
	        } 
	        if($('s'+i)) {
	            $('s'+i).show();	            
	        }

	    }        

	} else {
        $('prev_button').show();
        $('next_button').show();
	    
	    $('date').setValue(date);
	    date2 = date.split(".",3);

	    //alert(selectedDate + ' ' + date);

	    if(selectedDate) {
	        currentdate2 = selectedDate.split(".",3);
	        if(date2[1] != currentdate2[1] || date2[2] != currentdate2[2]) {
	            var month = parseInt(date2[1]);
	            //alert(month);
	            //alert('service=calendar.getPickerHtml&year='+date2[2]+'&month='+month+'&dateInputElementId=date&calendarElementId=cal&firstAvailableDate='+date);
	            new Ajax.Updater('cal', '/xmlhttprequest.php' , { asynchronous:true, evalScripts:true, parameters:'service=calendar.getPickerHtml&year='+date2[2]+'&month='+month+'&dateInputElementId=date&calendarElementId=cal&firstAvailableDate='+date, method:'get'});
	            setTimeout('addHighlight('+date2[0]+')',500);
	        } else if(date2[0] != currentdate2[0]) {
	            var month = parseInt(date2[1]);
	            //alert(month);
	            new Ajax.Updater('cal', '/xmlhttprequest.php' , { asynchronous:true, evalScripts:true, parameters:'service=calendar.getPickerHtml&year='+date2[2]+'&month='+month+'&dateInputElementId=date&calendarElementId=cal&firstAvailableDate='+date, method:'get'});
	            setTimeout('addHighlight('+date2[0]+')',500);
	        }
	    }
	    //selectedDate = date;
	    changeDate(date2[2]+'-'+date2[1]+'-'+date2[0]);

	    var cells = 0;
	    var cells2 = 0;
	    var reps = 0;
	    var reps2 = 0;

	    var na = $$('#lb_service #cal td.na');
	    na.each(function(item) {
	        item.removeClassName('na');
	        cells++;
	    });

	    var replacements = $$('#lb_service #cal td span.replacement');
	    replacements.each(function(item) {
	        item.hide();
	        reps++;
	    });

	    var notc = 0;

	    for(i=1;i<=31;i++) {
	        if($('c'+i)) {
	            if(i < date2[0]) {
	                $('c'+i).addClassName('na');
	                cells2++;
	            }
	        } else {
	            notc++;
	        }

	        if($('s'+i)) {
	            $('s'+i).show();
	            reps2++;
	        }

	    }
     
	}
    
}


function toggleTechnicalSpecifications(id) {
	// if element has a certain class, blindUp + remove class
	// else blindDown + add class
	if ($('main_infolink' + id).hasClassName('arrow_down')) {
		new Effect.BlindUp('main_info'+id,{duration: 1});
		$('main_infolink' + id).update('Vis tekniske spesifikasjoner');
	} else {
		$('main_infolink' + id).update('Skjul tekniske spesifikasjoner');
		new Effect.BlindDown('main_info'+id,{duration: 1});
	}
	$('main_infolink'+id).toggleClassName('arrow_down');
}

function readMore(id) {
	// if element has a certain class, blindUp + remove class
	// else blindDown + add class
	if ($('main_infolink' + id).hasClassName('arrow_down')) {
		new Effect.BlindUp('main_info'+id,{duration: 1});
		$('main_infolink' + id).update('Les mer');
	} else {
		$('main_infolink' + id).update('Skjul tekst');
		new Effect.BlindDown('main_info'+id,{duration: 1});
	}
	$('main_infolink'+id).toggleClassName('arrow_down');
}

function updateCustomerServiceStatus(img,lb) {
    if(lb) {
        if($('ks_status_lb')) {
            $('ks_status_lb').writeAttribute("src",img);    
        }
    } else {
        if($('ks_status_lb')) {
            $('ks_status').writeAttribute("src",img);    
        }
    }
}

function togglehighlight(element) {
    $(element).toggleClassName('highlight');    
}


function addHighlight(elementid) {
    if($('d'+elementid) && !alreadyAdded) {
        $('d'+elementid).toggleClassName('selected');        
        alreadyAdded = true;
        /*Lag ny funksjon som setter alreadyAdded til false etter 1-2sek*/
    }
}




function changeBg(key) {        
    $('chassicontainer').setStyle({
        backgroundImage: 'url('+bgImages.get(key)+')'
    });    
}

function validate(date) {  
    
    /*
    TODO: Sjekk om dag er lørdag eller søndag.
    TODO: Sjekk om dag er 10 tegn lang.
    TODO
    */
      
    if (date.search(/^\d{1,2}[\.|_]\d{1,2}[\.|_]\d{4}/g) != 0) {
        alert("Galt datoformat, vennligst korriger til DD.MM.YYYY");
    } else {
        availdate = availableDates.get($('department').getValue());
        
        date1 = date.split(".",3);
        date2 = availdate.split(".",3);
        
        error = false;
        if(date1[2] < date2[2]) {  
            error = true;
        }
        if(date1[1] < date2[1]) {            
            error = true; 
        }
        if(date1[0] < date2[0]) {            
            error = true;            
        }
        
        if(error) {
            alert("Datoen du har skrevet inn er før den valgte butikken har ledig tid, vennligst korriger.");
        }    
    }

}


function openNewLightbox(url) { 
	
      if(lightbox.isVisible()) {
          lightbox.hide();
      }      
      // set lightbox flash attribute
      lightbox.isOpenedFromFlash = true;
      setTimeout('lightbox.show(\''+url+'\');',100);        
}

var bgImages;


function rohneselmerResizeVideoLightbox(width, height) {
	// resize lightbox-container (calculate margins/paddings)
	// resize flashvideolightbox to width x height
	$('lightbox-container').setStyle({
		width: (width + 0) + "px",
		height: (height + 30 + 25) + "px"
//		backgroundColor: "#ffe0e0"
	});
	$('flashvideolightbox').setStyle({
		width: width + "px",
		height: (height + 25) + "px",
		margin: "0",
		padding: "0"
	});
	$('flashvideolightbox').down('div').setStyle({
		width: width + "px",
		height: (height + 25) + "px",
		margin: "0",
		padding: "0"
	});
}


