﻿var Product = new Class({
    kind:-1,
    price: 0,
    period: 0,
    name:""
});

var Products=new Array();


var JoinManager = new Class({
    currentStep: 0,
    currentBar: 0,
    currentVassel: 0,
	currentVasselType:"",
    currentColor: 0,
    vasselPrice: 0,
    vasselQuantity: 1,
    productPrice: 0,
    productPeriod: 0,
    productType: 0,
    totalPrice: 0,
    initialize: function() {

    },
    gotoStep: function(stepId) {
		if (stepId == 2 && this.currentBar==0){
			this.openMessageWindow("שגיאה","לא נבחר בר<br/>בחר בר ולחץ המשך");
			return;
		}
		if (stepId == 3 && this.currentVassel==0){
			this.openMessageWindow("שגיאה","לא נבחר כד<br/>בחר כד ולחץ המשך");
			return;
		}
		
        if (stepId == this.currentStep)
            return;
        try {
            $('step' + this.currentStep).hide();
        }
        catch (e) { }
        $('step' + stepId).show();

        // show last step msg
        if (stepId == 4) {
            try {
				this.showSelectedBarAndVassel();
				_gaq.push(['_setCustomVar', 1, 'visitor-type', 'lead-join', '1']);
				_gaq.push(['_trackPageview', '/virtual/join/step4/thankyou']);
                thisMovie("mainFlash").showBus();
            }
            catch (e) { 
			}
            
        }
		
		if (stepId==3){
			this.fillStep3Details();
			_gaq.push(['_trackPageview', '/virtual/join/step3/userdetails']);
			$('priceInformationBox').hide();
			$('step3PriceInformationBox').show();
		}
		else{
			$('priceInformationBox').show();
			$('step3PriceInformationBox').hide();
		}
		
		 if (stepId==1)
            _gaq.push(['_trackPageview', '/virtual/join/step2/choosebar']);
		
        if (stepId==2)
            _gaq.push(['_trackPageview', '/virtual/join/step2/choosecad']);
        this.currentStep = stepId;

    },
	showSelectedBarAndVassel:function(){
		//this.currentVasselType="small";
		var currentVasselElement=null;
		if (this.currentVasselType == "small"){
				$("step4_smallVassel").addClass("hidden");
				$("step4_bigVassel").addClass("hidden");
				currentVasselElement=$("step4_smallVassel");
			}
            else{
                $("step4_bigVassel").addClass("hidden");
				$("step4_smallVassel").addClass("hidden");
				currentVasselElement=$("step4_bigVassel");
			}
		var imgElement=$('selectedBarImage');
		 var currentImage=thisMovie("mainFlash").getCurrentImage(this.currentBar, this.currentColor);
		 
		imgElement.src=currentImage;	
        imgElement.hide();
        var myImage = new Asset.image(imgElement.src, { id: imgElement.id, title: imgElement.alt, onload: function(e) {
				(function(){
					imgElement.show();
					currentVasselElement.style.bottom=imgElement.getSize().size.y.toString()+"px";
					currentVasselElement.style.left=((imgElement.getSize().size.x-57)/2)+"px";
					currentVasselElement.removeClass("hidden");
				}).delay(1000);
				}
			});
		
		
	},
	fillStep3Details: function(){

			var vasselId=this.currentVassel;
			var barName = unescape(Products[this.currentBar].name);
            var barPrice = Products[this.currentBar].price;
            var priceType = Products[this.currentBar].kind;

            var vasselName = Products[vasselId].name;
            var vasselSelectElement = $$('#product_' + vasselId + ' .quantitySelect')[0];
           

            var vasselQuantity = vasselSelectElement.options[vasselSelectElement.selectedIndex].value;
            var vasselPrice = Products[vasselId].price;

            var vasselName = vasselQuantity + " x " + vasselName;

            if (this.productType == 1) {
                var prodPrice = 'תשלום חד פעמי: ';
				var realPrice=parseFloat(this.productPrice / this.productPeriod);
				if (realPrice-parseInt(realPrice)!=0){
					realPrice=parseInt(realPrice)+((parseInt((realPrice-parseInt(realPrice))*10))/10);
				}			
                prodPrice += "₪" + realPrice + "x" + this.productPeriod;
            }
            else {
                var prodPrice = 'תשלום חודשי: ';
                prodPrice += "₪" + parseFloat(this.productPrice);

            }

            $('step3_QuantityAndName').innerHTML = vasselName;
            $('step3_MonthlyPrice').innerHTML = "₪" + vasselPrice * vasselQuantity;
            $('step3_Price').innerHTML = prodPrice;
            $('step3_Price2').innerHTML = prodPrice;

            $('step3_BarName').innerHTML = barName;
            $('step3_Total').innerHTML = parseInt(servicePrice) + parseInt(vasselPrice * vasselQuantity);
            $('step3_monthlyTotal').innerHTML = servicePrice ;
	}
	,
    sendFormAndGotoStep4: function() {
        if ($('SendingFormMsg').hasClass('hidden')) {
            if (validateForm(document.forms['joinForm'])) {
                $('SendingFormMsg').removeClass('hidden');
            };
        }
        return false;
        // this.gotoStep(4);
    },
    updatePrice: function(productId, isVassel) {
        try {
            var price = parseFloat(Products[productId].price);
            var kind = parseFloat(Products[productId].kind);
            var period = parseFloat(Products[productId].period);

            if (!isVassel)//update product information
            {
                this.productPrice = price;
                this.productType = kind;
                this.productPeriod = period;
            }
            else
                this.vasselPrice = price;

            // alert(this.productPrice + "--" + this.productType + "--" + this.vasselPrice + '--' + servicePrice);


            $('service_price').innerHTML = parseFloat(servicePrice);
            $('vasel_price').innerHTML = parseFloat(this.vasselPrice)+"x"+parseFloat(this.vasselQuantity);
            if (this.productType == 1) {
				var realPrice=parseFloat(this.productPrice / this.productPeriod);
				if (realPrice-parseInt(realPrice)!=0){
					realPrice=parseInt(realPrice)+((parseInt((realPrice-parseInt(realPrice))*10))/10);
				}
                $('bar_price').innerHTML =  realPrice+ "x" + this.productPeriod;
                $('bar_price_type').innerHTML = 'תשלום חד פעמי';
                $('oneTime_price').innerHTML = realPrice + "x" + this.productPeriod;
                $('grandTotal_price').innerHTML = parseFloat(this.vasselPrice) * parseFloat(this.vasselQuantity) + servicePrice;
				
                this.totalPrice = parseFloat(this.vasselPrice) * parseFloat(this.vasselQuantity) + servicePrice;
            }
            else {
                $('bar_price_type').innerHTML = 'תשלום חודשי';
                $('bar_price').innerHTML = parseFloat(this.productPrice);
                $('oneTime_price').innerHTML = '0';
                $('grandTotal_price').innerHTML = (this.productPrice + parseFloat(this.vasselPrice) * parseFloat(this.vasselQuantity) + servicePrice);
                this.totalPrice = (this.productPrice + parseFloat(this.vasselPrice) * parseFloat(this.vasselQuantity) + servicePrice);
            }
        }
        catch (e) {
            // alert(e);
        }
    },
    selectBar: function(barId) {

        if (barId == this.currentBar)
            return;

        try {
            $('product_' + barId).addClass('selected');
            $('product_' + this.currentBar).removeClass('selected');
        }
        catch (e) { }
        finally {
            this.currentBar = barId;
			this.currentColor=0;
            this.updatePrice(barId, false) // update bar price (true will update vassel price)
        }
        try {

            thisMovie("mainFlash").selectBar(barId, this.currentColor, this.currentVasselType);
        }
        catch (e) { }
    },
    selectColor: function(barId, colorId) {
        if (this.currentBar != barId) {
            try {
                $('product_' + barId).addClass('selected');
                $('product_' + this.currentBar).removeClass('selected');
            }
            catch (e) { }
            finally {
                this.currentBar = barId;
                this.updatePrice(barId, false) // update bar price (true will update vassel price)
            }
        }
        this.currentColor = colorId;
        try {
			//console.log(barId, colorId, this.currentVasselType);
            thisMovie("mainFlash").selectBar(barId, colorId, this.currentVasselType);
        }
        catch (e) { }
    },
    selectVassel: function(vasselId) {

        if (vasselId == this.currentVassel)
            return;

        try {
            $('product_' + vasselId).addClass('selected');
			if ($('product_' + this.currentVassel))
				$('product_' + this.currentVassel).removeClass('selected');
            var vasselSelectElement = $$('#product_' + vasselId + ' .quantitySelect')[0];
            this.vasselQuantity = vasselSelectElement.options[vasselSelectElement.selectedIndex].value;
        }
        catch (e) { 
		//	alert(e);
		}
        finally {
            this.currentVassel = vasselId;
            this.updatePrice(vasselId, true) // update vassel price
        }
        try {
            if ((Products[vasselId].name + '').indexOf("11") > -1)
                this.currentVasselType = "small";
            else
                this.currentVasselType = "big";
			//console.log(this.currentBar+'--'+ this.currentColor+'--'+ this.currentVasselType);
            thisMovie("mainFlash").selectBar(this.currentBar, this.currentColor, this.currentVasselType );
        }
        catch (e) {
            //alert(this.currentVassel);
        }
    },
    changeQuantityForVassel: function(vasselId, selectedQuantity) {
        try {
            var vasselPrice = Products[vasselId].price;
            $$('#product_' + vasselId + ' .vasselPrice')[0].innerHTML = (vasselPrice * selectedQuantity);
			//make this selected vassel
			this.selectVassel(vasselId);
            if (this.currentVassel == vasselId) {
                var vasselSelectElement = $$('#product_' + vasselId + ' .quantitySelect')[0];
                this.vasselQuantity = vasselSelectElement.options[vasselSelectElement.selectedIndex].value;
                this.updatePrice(vasselId, true);
            }
        }
        catch (e) {
			//alert(e);
        }
    },
    openVasselLightBox: function(vasselId) {
        
        $('productInformation').hide();
        $('VasselInformation').show();
        $('informationTitle').innerHTML = "מידע נוסף";
        try {
            $$(".quantitySelect").each(function(el,idx){
             el.disabled = true;
            });
            var barName = unescape(Products[this.currentBar].name);
            var barPrice = Products[this.currentBar].price;
            var priceType = Products[this.currentBar].kind;

            var vasselName = Products[vasselId].name;
            var vasselSelectElement = $$('#product_' + vasselId + ' .quantitySelect')[0];
           

            var vasselQuantity = vasselSelectElement.options[vasselSelectElement.selectedIndex].value;
            var vasselPrice = Products[vasselId].price;

            var vasselName = vasselQuantity + " x " + vasselName;

            if (this.productType == 1) {
                var prodPrice = 'תשלום חד פעמי: ';
				var realPrice=parseFloat(this.productPrice / this.productPeriod);
				if (realPrice-parseInt(realPrice)!=0){
					realPrice=parseInt(realPrice)+((parseInt((realPrice-parseInt(realPrice))*10))/10);
				}			
                prodPrice += "₪" + realPrice + "x" + this.productPeriod;
            }
            else {
                var prodPrice = 'תשלום חודשי: ';
                prodPrice += "₪" + parseFloat(this.productPrice);

            }

            $('vasselInformation_QuantityAndName').innerHTML = vasselName;
            $('vasselInformation_MonthlyPrice').innerHTML = "₪" + vasselPrice * vasselQuantity;
            $('vasselInformation_Price').innerHTML = prodPrice;
            $('vasselInformation_Price2').innerHTML = prodPrice;

            $('vasselInformation_BarName').innerHTML = barName;
            $('VasselInformation_Total').innerHTML = parseInt(servicePrice) + parseInt(vasselPrice * vasselQuantity);
            $('vasselInformation_monthlyTotal').innerHTML = servicePrice 

            MoreInformationLightbox.Open();
        }
        catch (e) {
            // console.log(e);
        }
    },
    openInfoLightBox: function(barId) {
        $('productInformation').show();
        $('VasselInformation').hide();
        try {
			$$('#productInformation .bottomSale').show();
            var description = $$('#product_' + barId + ' .moreInformation')[0].innerHTML;
            $('informationContent').innerHTML = description;
            var title = $$('#product_' + barId + ' .header')[0].innerHTML;
            $('informationTitle').innerHTML = title;
            MoreInformationLightbox.Open();
        }
        catch (e) {
            //console.log(e);
        }
    },
	 openMessageWindow: function(title,text) {
	  $$(".quantitySelect").each(function(el,idx){
             el.disabled = true;
            });
		 $('productInformation').show();
        $('VasselInformation').hide();
		$$('#productInformation .bottomSale').hide();
		$('informationTitle').innerHTML = title;
		$('informationContent').innerHTML = text;
		 MoreInformationLightbox.Open();
	 }
});
var jManager;
$DL(function() {
    jManager = new JoinManager();
    MoreInformationLightbox.Init();
    var vasselType = "";
    var flashvars = {};
    flashvars.xmlPath = "joinXml.asp";
    flashvars.currentBarId = jManager.currentBar;
    flashvars.currentColorId = jManager.currentColor;
	flashvars.debug = "false";
    flashvars.ballonSize = vasselType;

    var params = {};
    params.wmode = 'transparent';
    var attributes = {};
    attributes.id = "mainFlash";
    swfobject.embedSWF("flash/joinMainFlash.swf", "flashHolder", "189", "218", "9.0.0", false, flashvars, params, attributes);
	
	attributes = {};
	flashvars = {};
	swfobject.embedSWF("flash/join_banner.swf", "bannerHolder", "186", "80", "9.0.0", false, flashvars, params, attributes);
	
	

});

var MoreInformationLightbox = {
    Lightbox: null,
    Init: function() {
        wrapperId = "moreInformationLightBox";
        MoreInformationLightbox.Lightbox = new Lightbox($(wrapperId));
        if ($("closeMoreInformationButton")) $("closeMoreInformationButton").addEvent("click", MoreInformationLightbox.Close);
    },

    Open: function() {
		$('moreInformationLightBox').show();
        MoreInformationLightbox.Lightbox.show();
    },
    Close: function() {
        try {
            $$(".quantitySelect").each(function(el, idx) {
                el.disabled = false;
            });
        }
        catch (e) { }
		$('moreInformationLightBox').hide();
		
        MoreInformationLightbox.Lightbox.hide();
    }

};


function validateForm(oForm) {
    var err = 0;
    $('fNameError').addClass('hidden');
    $('phoneError').addClass('hidden');
    $('EmailError').addClass('hidden');
       
    
    if (oForm.fName.value == "" && err == 0) {
        $('fNameError').removeClass('hidden');
        oForm.fName.focus();
        err++;
    }

    if (oForm.phone.value == "" && err == 0) {
        $('phoneError').innerHTML = "(שדה חובה)";
         $('phoneError').removeClass('hidden');
        oForm.phone.focus();
        err++;
    }
   
    if (!checkPhone(oForm.phone.value) && err == 0) {
        $('phoneError').innerHTML = "(טלפון לא תקין)";
        $('phoneError').removeClass('hidden');
        oForm.phone.focus();
        err++;
    }

    if (oForm.email.value != "" && !validateEmail(oForm.email.value)) {
        $('EmailError').removeClass('hidden');
        oForm.email.focus();
        err++;

    }


    if (err == 0) {
        try {
            var chosenMachine = Products[jManager.currentBar].name;
            var chosenColor = Products[jManager.currentBar].name;
            var chosenJug = Products[jManager.currentVassel].name;
            var jugAmount = jManager.vasselQuantity;
            var name = oForm.fName.value;
            var phone =  oForm.phone.value+" - " +oForm.phone_prefix.options[oForm.phone_prefix.selectedIndex].value;
            var email = oForm.email.value;
            var checkbox1Value = oForm.checkbox1.checked;
            var checkbox2Value = oForm.checkbox2.checked;
            var checkbox3Value = oForm.checkbox3.checked;
            var price = jManager.totalPrice;

            var url = "newjoinPost.asp?";

            var data = Object.toQueryString({ action: "register", chosenMachine: chosenMachine, chosenColor: chosenColor, chosenJug: chosenJug, jugAmount: jugAmount, name: name, phone: phone, email: email, checkbox1Value: checkbox1Value, checkbox2Value: checkbox2Value, checkbox3Value: checkbox3Value, price: price });
            var ajaxSender = new Ajax(url + data, { method: 'get' });
            ajaxSender.addEvent('onComplete', eventJoinRequestComplete);
            ajaxSender.addEvent('onFailure', eventJoinRequestFailed);

            ajaxSender.request();
        }
        catch (e) {
           // alert(e);
        }
        return true;
    }
    else
        return false;
}


function eventJoinRequestFailed(response) {
    $('SendingFormMsg').addClass('hidden');
    alert('השליחה נכשלה, נסה שוב בעוד מספר דקות. תודה.');
    //jManager.gotoStep(4);
}

function eventJoinRequestComplete(response) {
   // alert(response);
    $('SendingFormMsg').addClass('hidden');
    jManager.gotoStep(4);
}

function thisMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    var nAgt = navigator.userAgent;
    var majorVersion = 0;
    var fullVersion = 0;

    if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
        fullVersion = parseFloat(nAgt.substring(verOffset + 5));
        majorVersion = parseFloat('' + fullVersion);
    }
    if (isIE) {
        if (majorVersion >= 6) return document[movieName];
        return window[movieName];
    }
    return document[movieName];
}





