var $j = jQuery.noConflict();

if(typeof configuratorPage == "undefined"){configuratorPage = false;}
if(typeof orderPage == "undefined"){orderPage = false;}
	
	
$j(document).ready(function(){
    //PRETTYPHOTO
    $j("a[rel^='prettyPhoto']").prettyPhoto({
			opacity: 0.80, /* Value between 0 and 1 */
			show_title: false, /* true/false */
			allow_resize: false, /* Resize the photos bigger than viewport. true/false */
			default_width: 800,
			default_height: 600,
			theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
			horizontal_padding: 20, /* The padding on each side of the picture */
			modal: false, /* If set to true, only the close button will close the window */
			deeplinking: false, /* Allow prettyPhoto to update the url to enable deeplinking. */

			keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
			changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
			callback: function(){}, /* Called when prettyPhoto is closed */
			ie6_fallback: true,
			social_tools: false
		});


	//CONFIGURATOR DOCUMENT READY FUNCTIONS
	if(configuratorPage){

		$j("#priceTotal").val(baseConfigPrice.toFixed(2));
		$j("#weightTotal").val(baseConfigWeight);
		
		if(PIDgetParam){
			initWithPIDparam();
		}


	$j(".jqzoom").jqzoom({	zoomWidth: 250,
            				zoomHeight: 261,
            				preloadText: 'Lade Zoom',
            				title: false,
	});
		doCalc();
	}
	
	//ORDERPAGE DOCUMENT READY FUNCTIONS
	if(orderPage){
		//fires update event
		$j("#dealerZIP").keyup(searchDealer);
	
		//hide elements in printview mode
		if(printview) {
			$j("#dealerDiv").remove();
			$j("#adressDiv").remove();
			$j("#noticeDiv").remove();
			$j("#printButton").remove();
			$j("#saveOrder").remove();
			$j("#changeConfigButton").remove();
			
			$j.get(	"index.php?section=bikes&cmd=getDealerNameSessionVar&standalone=true",
					function(data){
						$j("#fieldsetDealer").html("<legend>Authorisierter Mondia Partner</legend>"+data);
						$j("#fieldsetDealer").css("display", "block");
					}
			);
		}

	}
});


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CONFIGURATOR
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function initWithPIDparam(){
	var PIDexplode = PIDgetParam.split('-');

	for(i = 0; i < PIDexplode.length; i++){
        if(arrProducts[PIDexplode[i]] != undefined){
            changeProduct(PIDexplode[i], arrProducts[PIDexplode[i]].partID, true);
        }
	}
	
	doCalc();
}



function changeProduct(productID, partID, fromInit){
	if(typeof fromInit == "undefined"){
		fromInit = false;
	}
    
    
    productID = productID.toString();

	//update hidden input field rightside
	$j('#id_bugfix_part_'+partID).val(productID);
	
	//update produdct name for part rightside
	$j('#nameFor_part_'+partID).html(arrProducts[productID].name);

    //check if part got the default product assigned
    var assignedPID = $j("#id_bugfix_part_"+partID).val();

    //and if not mark the row as modificated
    if(assignedPID != arrParts[partID]){
        $j("#rightbarProductsRow_"+partID).css('color', '#bd0f00');
        $j("#LI_MainProduct_Part_"+partID+"_Product_"+arrParts[partID]).css('display', 'block');
    } else {
        $j("#rightbarProductsRow_"+partID).css('color', '#505458');
        $j("#LI_MainProduct_Part_"+partID+"_Product_"+arrParts[partID]).css('display', 'none');

    }

    //this means is the label "wählen sie xxx als optionales zub..."
    if(productID.substr(0,4) == "9999"){
        $j("#activeValueSpan_part_"+partID).html(arrProducts[productID].name);
    } else {
        if(arrProducts[productID].price == ""  || arrProducts[productID].price == 0){
            if(arrProducts[productID].weight == "" || arrProducts[productID].weight == 0){
                $j("#activeValueSpan_part_"+partID).html(arrProducts[productID].name);
            } else {
                $j("#activeValueSpan_part_"+partID).html(arrProducts[productID].name+" ("+arrProducts[productID].weight+" g)");
            }
        } else {
            arrProducts[productID].price = parseInt(arrProducts[productID].price).toFixed(2);
            if(arrProducts[productID].weight == "" || arrProducts[productID].weight == 0){
                $j("#activeValueSpan_part_"+partID).html(arrProducts[productID].name+" ("+arrProducts[productID].price+" CHF)");
            } else {
                $j("#activeValueSpan_part_"+partID).html(arrProducts[productID].name+" ("+arrProducts[productID].price+" CHF / "+arrProducts[productID].weight+" g)");
            }
        }
    }

    //make all product options ==> LIs visible
    var lis = $j('[id^="LIforPart_'+partID+'_Product_"]');

    
    if(!fromInit){
        for(i=0; i<lis.length; i++){
            $j(lis[i]).css('display', 'block');
        }
    }

    //hide currently choosen product in dropdown list
    $j("#LIforPart_"+partID+"_Product_"+productID).css('display', 'none');


	//if calling from initWith...() we do it later for performance reasin
	if(!fromInit){
		doCalc();
	}
}


function formatPrice(str){
	switch(str.length){
		case 3:
			var preComma = str.substr(0,1);
			var lastComma = str.substr(1,2);
			var formatted = str;
			break;
		case 4:
			var preComma = str.substr(0,1);
			var lastComma = str.substr(1,3);
			var formatted = preComma+"'"+lastComma;
			break;
	}
	
	return formatted;
}
	

function doCalc(){
	//create array of product ids
	var arrInput = $j('input[id^="id_bugfix_part_"]');
	
	var price = baseConfigPrice;
	var weight = 0;
	var arrPID = new Array();

	//create array of product ids
	$j.each(arrInput, function(index, value) { 
		var pid = $j(value).val();
		
		//if we got a product id and pid is not 0 (means is equipment part which is not choosen)
		if(pid && pid != 0) {
			arrPID.push(pid);
		}
	});
    
	//do request
	$j.getJSON(	'modules/bikes/productsAndParts.AJAXrequest.php?getThis=productsFrontend&langID='+langID+'&editionID='+editionID+'&baseConfigID='+baseConfigID+'&arrPID='+arrPID,
        function(data) {

            $j.each(data, function(key, val) {
                if(key == 'products'){
                    $j.each(val, function(productsKey, productsVal) {
                        //set weight
                        if(productsVal.weight){
                            weight = weight + parseFloat(productsVal.weight);
                        }

                        //set price
                        // !== ' ' is needed because we need to fix input validation in edition add/eddit => aufpreis
                        if(productsVal.price !== '' && productsVal.price !== ' '){
                            price  = price + parseFloat(productsVal.price);
                        }

                        //update hidden input fields
                        $j("#weightTotal").val(weight);
                        $j("#priceTotal").val(price.toFixed(2));

                        //update font tags
                        //round
                        weightInKg = (weight/1000).toFixed(1);
                        $j("#weightTotalFont").html('Gewicht '+weightInKg+' kg');

                        formattedPrice = formatPrice(price.toFixed(0));

                        $j("#priceTotalFont").html('CHF '+formattedPrice+'.-');
                        //$j("#priceTotalFont").html('CHF '+price.toFixed(2));
                    });
                }

                if(key == 'images'){
                    $j('#editionPicSmall').attr('src', val.pathSmall);
                    $j('#editionPicLarge').attr('href', val.pathLarge);
                    $j('#imageZOOMDLink').attr('href', val.pathLarge);
                }
            });
        }
    );
}








//show / hiddes the additionalProducts DIV
function showHideProducts(partID) {
//    $j("#productRow_"+partID+' a').css('color', '#FFFFFF');
//	$j("#productRow_"+partID).css('color', '#FFFFFF');
//
//	$j("#productRow_"+partID).css('background', '#bd0f00');
//	$j("#rightbarProductsRow_"+partID).css('color', '#bd0f00');

	$j("#productRowOptions_"+partID).toggle("blind", 200);
}



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

















///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ORDERPAGE
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



function initGmap(longitude, latidude) {
	if(longitude == "" || latidude == ""){
		$j("#dealerMap").html('Es tut uns leid, wir können Ihnen für diesen Händler leider keine Karte anbieten.');
		$j("#dealerMap").css('background', 'white');
		return;
	}
    
    var latlng  = new google.maps.LatLng(longitude, latidude);
    var map     = new google.maps.Map(
        document.getElementById('dealerMap'),
        {
            zoom: 16,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.HYBRID
        }
    );

    var posPin = new google.maps.Marker(
        {
            position: latlng,
            map: map
        }
    );
}




//opens printview popup
function openPrintPage(){
	wnd = window.open("index.php?section=bikes&cmd=order&printview=1", "PrintPopUp", "width=800,height=800,status=yes,scrollbars=yes,resizable=yes");
 	wnd.focus();
}


function changeConf(pidString){
	window.location.href = document.referrer+'&pids='+pidString;
}


function setDealer(id){
	var id = id.replace('dealerLI_', '');
	var arrDealer = JSONdealer[id];

	$j("#dealerMap").css('display', 'block');
	$j("#dealerMap").html('<img src="images/modules/bikes/loader.gif" alt="images/modules/bikes/loader.gif">');
	
	$j("#dealerOptions").css('display', 'none');
	
	//update details
	$j("#dealerDetails").html(arrDealer['name']+'<br />'+arrDealer['street']+'<br />'+arrDealer['zip']+' '+arrDealer['city']+'<br /><br />Telefon: '+arrDealer['phone']+'<br />Telefax: '+arrDealer['fax']+'<br />'+arrDealer['homepage']);
	
	$j("#dealerZIP").val(arrDealer['name']);
	$j("#dealerID").val(id);
	$j.get("index.php?section=bikes&cmd=setDealerNameSessionVar&standalone=true&name="+arrDealer['name']);

	$j.getJSON(	"modules/bikes/dealers.AJAXrequest.php?get=coordinates&adress="+arrDealer['street']+" "+arrDealer['zip']+" "+arrDealer['city'],
				function(data) {
                    initGmap(data.long, data.lat);
				}
	);
}


function searchDealer(){
	//display search li
	$j("#dealerOptions").css('display', 'block');
	$j("#dealerOptions").html('<img src="images/modules/bikes/loader.gif" alt="images/modules/bikes/loader.gif">');
	$j("#dealerDetails").html('');
	$j("#dealerMap").css('display', 'none');

	$j.getJSON(	"modules/bikes/dealers.AJAXrequest.php?getDealersWith="+$j("#dealerZIP").val(),
        function(data) {
		    $j("#dealerOptions").html(data.search);
			setJSONDealer(data.dealer);
        }
	);
}


JSONdealer = "";
function setJSONDealer(JSONresponse){
	JSONdealer = "";
	JSONdealer = JSONresponse;	
}


function checkInput(isDealer){
	if(isDealer){
       return true;
    }

    var error     = false;
	var arrFields = new Array();
	
	arrFields.push("dealerID");
	arrFields.push("prename_billing");
	arrFields.push("lastname_billing");
	arrFields.push("street_billing");
	arrFields.push("city_billing");
	arrFields.push("zip_billing");
	arrFields.push("phone_billing");
	arrFields.push("email_billing");

    //unmark fields
	for(i = 0; i < arrFields.length; i++ ){
		$j("#"+arrFields[i]).css('border', "1px solid #000000");
	}

    
	for(i = 0; i < arrFields.length; i++ ){
        if(!$j("#"+arrFields[i]).val()){
			if(arrFields[i] == "dealerID"){
                arrFields[i] = "dealerZIP";
            }

            $j("#"+arrFields[i]).css('border', "1px solid red");
			error = true;
		}

        if(arrFields[i] == "email_billing"){
            if(!emailIsValid($j("#"+arrFields[i]).val())){
                $j("#"+arrFields[i]).css('border', "1px solid red");
                error = true;
            }
        }
	}
	
	if(error){
		return false;
	}
	
	return true;
}

function emailIsValid(str) {
    var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if(pattern.test(str)){
		return true;
    }else{
		return false;
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function botControl(f,i,l){
	str = f+'@'+'tic'+'.'+l;
	$j('#'+i).html('<a href="mailto:'+str+'">'+str+'<\/a>');
}


/****NAVIGATION PREVIEW PICTURE**********/
function showPreviewIMG(id){
    if(id == 'mouseOut'){
        $j('#previewPicLoc').hide();
    } else {
        $j('#previewPicLoc').show();
        $j('#previewPicIMG').hide();
        $j('#previewPicSpinner').show();

        $j('#previewPicIMG').attr('src', id).load(function(){
            $j('#previewPicSpinner').hide();
            $j(this).show();
        });
    }
}
/****NAVIGATION PREVIEW PICTURE**********/




/******SCROLLING RIGHTBAR*****************/
$j(document).ready(function(){
    var barType = "rightbarConfigContent";
    
    if($j('#rightbarConfigContent').length == 0){
        barType = "rightbarContent";
    }

    var rightbarContentHeight = $j('#'+barType).innerHeight();
    var windowHeight = $j(window).height();
    var diff = "";

    if(rightbarContentHeight > windowHeight){
        var diff = rightbarContentHeight-windowHeight;
    }

    var msie6 = $j.browser == 'msie' && $j.browser.version < 7;

    if (!msie6) {
    var top = $j('#'+barType).offset().top - parseFloat($j('#'+barType).css('margin-top').replace(/auto/, 0));

    $j(window).scroll(function (event) {

    // what the y position of the scroll is
    var y = $j(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
    // if so, ad the fixed class
    $j('#'+barType).addClass('fixed');
    if(diff){
    //            alert("1");
    $j('#'+barType).css('top', "-"+diff+"px");
    }
    } else {
    // otherwise remove it
    $j('#'+barType).removeClass('fixed');
    if(diff){
    $j('#'+barType).css('top', "0px");
    }
    }
    });
    }



    var barType = "rightbarConfigContent";
        if($j('#rightbarConfigContent').length == 0){
            barType = "rightbarContent";
        }

        var rightbarContentHeight = $j('#'+barType).innerHeight();
        var containerHeight = $j('#container').innerHeight();
        var diff = "";

        //bigger then content
        if(rightbarContentHeight > containerHeight){
            var diff = rightbarContentHeight-containerHeight;
            $j("#container").css('height', ($j("#"+barType).innerHeight())+'px');
            $j("#rightbar").css('height', ($j("#"+barType).innerHeight())+'px');
        } else {
//            $j("#rightbar").css('height', ($j("#"+barType).innerHeight())+100+'px');
            $j("#rightbar").css('height', ($j("#container").innerHeight())+'px');
        }
        botControl("mondia", "botFooter", "ch");
    
});
/******SCROLLING RIGHTBAR*****************/
