﻿/**
 * cookie monster(basket)
 * jquery play portal basket (popup)
 * @author Lukasz Rozbicki - K2.pl
 */

 /* zmienne */
 _STRONA_ZBIORCZA_TELEFONY = '031_Telefony_zbiorcza.html';
 _STRONA_OFERTY_ABO = '015_Abonament_strona_oferty.html';
 _STRONA_ESHOP_KOSZYK = 'E12_koszyk_pelny.html';
 
/*=========================================
===========================================
=========================================*/

/* json stringify & parse */
var JSON = JSON || {}; 
JSON.stringify = JSON.stringify || function (obj) {
	var t = typeof (obj);
	if (t != "object" || obj === null) {
		// simple data type
		if (t == "string") obj = '"'+obj+'"';
		return String(obj);
	}
	else {
		// recurse array or object
		var n, v, json = [], arr = (obj && obj.constructor == Array);
		for (n in obj) {
			v = obj[n]; t = typeof(v);
			if (t == "string") v = '"'+v+'"';
			else if (t == "object" && v !== null) v = JSON.stringify(v);
			json.push((arr ? "" : '"' + n + '":') + String(v));
		}
		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
};
JSON.parse = JSON.parse || function (str) {
	if (str === "") str = '""';
	eval("var p=" + str + ";");
	return p;
};

var _cMB = {
    /* 'private' */
    _debug:             false,
    _monitShown:        false,
    _cookieName:        'cMB',
    _cookieExpires:     '',
    _cookiePath:        '/',
    _playboxTrigger:    jQuery('<a href="#"></a>'),
    _basketFull:        false,
	_offerType:			false, /* flaga typu oferty (abo,mix,karta) - tylko dla oferty! dla produktu false */
	_whereAmI:			'', /* flaga okreslajaca, gdzie jestesmy, czy na str. telefonów czy na ofercie */
	/* 'public' */
	NOW_ADDING:			'', /* flaga, co się teraz dodaje - product lub offer */
    
    __ifCookieExists: function(){
        return !(_cMB.__readCookie() == null);
    },
    __writeCookie: function(value){
        _cMB.__log('__writeCookie start');
        value = encodeURIComponent(JSON.stringify(value));
        document.cookie = _cMB._cookieName+"="+value+_cMB._cookieExpires+"; path="+_cMB._cookiePath;
        _cMB.__log('__writeCookie end');
    },
    __readCookie: function(){
        _cMB.__log('__readCookie start');
    	var nameEQ = _cMB._cookieName + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
	        var c = ca[i];
	        while (c.charAt(0)==' ') c = c.substring(1,c.length);
            _cMB.__log('__readCookie end true.'); 
	        if (c.indexOf(nameEQ) == 0){ 
	            _cMB.__log('I read: '+c.substring(nameEQ.length,c.length));
	            return c.substring(nameEQ.length,c.length);
	        }else{
	            _cMB.__log('Is no cookie with name U give :(');
	        }
        }
        _cMB.__log('__readCookie end false');
        return null;
    },
    __whatIsInside: function(newContent){ /* sprwadzenie, co jest w koszyku. Jesli to samo to return 1, jesli co innego to return 2, jesli nic to return 0 */
        newContent = encodeURIComponent(JSON.stringify(newContent));
        var tmpCookieContent = _cMB.__readCookie();
        if( tmpCookieContent == null || tmpCookieContent == 'null' ){
            _cMB.__log('Where is mah bucket? ;(((');
			_cMB._basketFull = false;
            return 0; 
        }else{
			_cMB._basketFull = true;
            /* sprawdzenie czy to co w koszyku to to co dodaję */
            if( tmpCookieContent == newContent ){
                _cMB.__log('I alredy has that!');
				return 1;
            }else{
                _cMB.__log('Woa, I not has this! Wanna change?');
				return 2;
            }
        };
    },
    __log: function(txt){
        if( _cMB._debug ) console.log('COOKIE MONSTER SAYS: '+txt);
    },
    
    /* constructor */
    init: function(){
		if( _cMB._debug ) window.loadFirebugConsole();
        _cMB.__log('I is alive!!!');
        if( _cMB.__whatIsInside() != 0 ){
            _cMB.__log('I has a cookie!!!');
            _cMB._basketFull = true;
        }else{
            _cMB.__log('I no has a cookie :(');
            _cMB._basketFull = false;
        };
		if( jQuery('#searchOffer').length && jQuery('fieldset.searchOffer').length ){
			_cMB._whereAmI = 'phones';
		}else if( jQuery('.cMB-phoneDetails').length ){
			_cMB._whereAmI = 'offer';
		};
        jQuery('body').delegate('.cartInfoLayer .del a','click',function(){ _cMB.removeFromBasket(); return false; });
    },
    
    /* 'public' */
    playboxTrigger: function(c){ _cMB.__log('playboxTrigger start'); _cMB._playboxTrigger.playbox({ source:c, method:'html' }).click(); },
    
	getContentName: function(withType){ /* wyciąga nazwę rzeczy z koszyka */
		var tmpC = _cMB.__readCookie();
		if( tmpC == null || tmpC == 'null' ) return false;
		var tmpContent = JSON.parse(decodeURIComponent(tmpC));
		if( tmpContent.length == 1 ){
			return (withType ? 'telefon ' : '') + tmpContent[0].telefon.d;
		}else if( tmpContent.length == 3 || tmpContent.length == 2 ){
			var tmpTypAbonamentu = null;
			var tmpWysokoscAbonamentu = null;
			var tmpChoosePromo = null;
			/* czesanie tmpContent w poszukiwaniu odpowiedniej zawartosci (obiektów) */
			for(c in tmpContent){
				var tmpBC = tmpContent[c];
				if( tmpBC.hasOwnProperty('typAbonamentu') ) tmpTypAbonamentu = tmpBC.typAbonamentu;
				if( tmpBC.hasOwnProperty('wysokoscAbonamentu') ) tmpWysokoscAbonamentu = tmpBC.wysokoscAbonamentu;
				if( tmpBC.hasOwnProperty('choosePromo') ) tmpChoosePromo = tmpBC.choosePromo;
			};
			return (withType ? 'abonament ' : '') + tmpTypAbonamentu.d + ' ' + (tmpWysokoscAbonamentu ? tmpWysokoscAbonamentu.v + 'zł' : '' )+ ' z promocją '+tmpChoosePromo.d;
		};
		return '';
	},
	getProductData: function(){ /* dotyczy TYLKO telefonu - wyciąganie zdjęcia z ciacha (url) */
		var tmpC = _cMB.__readCookie();
		if( tmpC == null || tmpC == 'null' ) return false;
		var tmpContent = JSON.parse(decodeURIComponent(tmpC));
		if( tmpContent.length == 1 ) return tmpContent[0].telefon;
	},
	getOfferData: function(){
		var tmpC = _cMB.__readCookie();
		if( tmpC == null || tmpC == 'null' ) return false;
		var tmpContent = JSON.parse(decodeURIComponent(tmpC));
		var tmpTypAbonamentu = null;
		var tmpWysokoscAbonamentu = null;
		var tmpChoosePromo = null;
		/* czesanie tmpContent w poszukiwaniu odpowiedniej zawartosci (obiektów) */
		for(c in tmpContent){
			var tmpBC = tmpContent[c];
			if( tmpBC.hasOwnProperty('typAbonamentu') ) tmpTypAbonamentu = tmpBC.typAbonamentu;
			if( tmpBC.hasOwnProperty('wysokoscAbonamentu') ) tmpWysokoscAbonamentu = tmpBC.wysokoscAbonamentu;
			if( tmpBC.hasOwnProperty('choosePromo') ) tmpChoosePromo = tmpBC.choosePromo;
		};
		return { tA: tmpTypAbonamentu, wA: tmpWysokoscAbonamentu==null?'':tmpWysokoscAbonamentu, p: tmpChoosePromo };
	},
    addToBasket: function(pJSON, redirectAsIs, chooseOtherPhone){ /* pJSON - json ze struktura produktu, ktory dodajemy do koszyka, redirectAsIs - parametr określający, że wybrana rzecz (w sumie tylko oferta) ma być dodana do koszyka tak jak jest (bez monitu, że mam już to w koszyku co dodaję) i robi się redirect do str. telefonów, chooseOtherPhone - zmienna sterująca monitem ICanHasANewBasket */
        _cMB.__log('addToBasket start');
        /* sprawdzenie, czy w koszyku juz jest */
        _cMB.__log('I check if basket filled');
        var tmpBasketState = _cMB.__whatIsInside(pJSON);
        if( tmpBasketState == 1 && !redirectAsIs ){
            _cMB.__log('basket not empty!');            
        /* jak mam juz ale inne niz dodaje confirm czy chce zamienic */
        /* jak yes to usuwam+dodaje/nadpisuje zawartosc koszyka */
            _cMB.__showMonit('IHasIt');
        }else if( tmpBasketState == 2 ){
            _cMB.__log('basket not empty! Want new basket?');
            _cMB.__showMonit( chooseOtherPhone ? 'IHasPhoneAndWantAnotherPhone' : 'ICanHasANewBasket', {
                cancel: { label: 'Powrót', action: 'abort' },
                ok: { label: 'Zamień', action: 'change', actionArgs: pJSON }
            });
        }else{
        /* jak nic nie ma to dodaje */
            _cMB.__log('basket empty! feed me!');
            _cMB.__writeCookie(pJSON);
			_cMB._basketFull = true;
			_cMB.genBasketHTML();
        }
        /*  */
    },
    removeFromBasket: function(){
		_cMB.__log('removeFromBasket start');
		/* wyczyszczenie koszyka, pokazanie monitu z tekstem, że koszyk pusty i po kilku sek. zamknięcie z automatu */
		_cMB.__writeCookie(null);
		_cMB._basketFull = false;
		_cMB.__showMonit('IHasEmptyBasket');
		setTimeout(function(){
			jQuery('#playboxClose a').click();
		},3000);
		_cMB.__log('removeFromBasket end');
	},

    genBasketHTML: function(){
		_cMB.__log('genBasketHTML start');
		var _basketContent = JSON.parse(decodeURIComponent(_cMB.__readCookie()));
		var tmpHTML = ['<div class="cartInfoLayer">'];
		tmpHTML.push('<p class="pi">Właśnie dodałeś do koszyka</p>');
		tmpHTML.push('<table class="eShopBasket marginBottom20" cellspacing="0" cellpadding="0"><thead><tr><th>&#160;</th><th class="eShopBasketHeader">Opłata jednorazowa</th><th class="eShopBasketHeader">Opłata miesięczna</th><th class="last">&nbsp;</th></tr></thead>');
		if( _cMB.NOW_ADDING == 'offer' ){
			/* tutaj html z tabelką */
			var tmpTypAbonamentu = null;
			var tmpWysokoscAbonamentu = null;
			var tmpChoosePromo = null;
			/* czesanie _basketcontent w poszukiwaniu odpowiedniej zawartosci (obiektów) */
			for(c in _basketContent){
				var tmpBC = _basketContent[c];
				if( tmpBC.hasOwnProperty('typAbonamentu') ) tmpTypAbonamentu = tmpBC.typAbonamentu;
				if( tmpBC.hasOwnProperty('wysokoscAbonamentu') ) tmpWysokoscAbonamentu = tmpBC.wysokoscAbonamentu;
				if( tmpBC.hasOwnProperty('choosePromo') ) tmpChoosePromo = tmpBC.choosePromo;
			};
			/* ---- */
			tmpHTML.push('<tr><td><strong>Abonament: '+tmpTypAbonamentu.d+'</strong><br />Promocja '+tmpChoosePromo.d+'</td><td class="emptyCell">&#160;</td><td class="price' + (tmpWysokoscAbonamentu?'':' emptyCell' ) + '">'+ (tmpWysokoscAbonamentu ? tmpWysokoscAbonamentu.v+' <small>zł</small>':'&#160;' ) + '</td><td class="del"><a title="Usuń" href="#" class="linkPointer linkPointerClose itemDel"><span>Usuń</span></a></td></tr>');
		}else if( _cMB.NOW_ADDING == 'product' ){
			/* tutaj html z tabelką */
			tmpHTML.push('<tr><td><strong>Telefon: '+_basketContent[0].telefon.d+'</strong></td><td class="price">'+_basketContent[0].telefon.p+' <small>zł'+/* + '+_basketContent[0].telefon.t+'% VAT</small>'*/ '</td><td class="emptyCell">&#160;</td><td class="del"><a title="Usuń" href="#" class="linkPointer linkPointerClose itemDel"><span>Usuń</span></a></td></tr>');
		};
		tmpHTML.push('</table>');
		var tmpConfirm = {
            cancel: { label: 'Powrót', action: 'abort' },
			ok: { label: _cMB.NOW_ADDING=='offer'?'Dobierz telefon':'Dobierz ofertę', action: _cMB.NOW_ADDING=='offer'?'redirectToPhones':'redirectToOffer' }
        };
		tmpHTML.push(_cMB.__insertConfirm(tmpConfirm));
		tmpHTML.push('</div>');
		_cMB.playboxTrigger( tmpHTML.join('') );
		jQuery('.pBC-Cancel').click(_cMB.__confirmAction(tmpConfirm.cancel.action));
		jQuery('.pBC-OK').click(_cMB.__confirmAction(tmpConfirm.ok.action));
		_cMB.__log('genBasketHTML stop');
    },
    
    /* monity */
    _monit_IHasIt: '<p>Już to masz!</p>',
	_monit_ICanHasANewBasket: '<p>W koszyku znajduje się już <br/><span id="contentName"></span>. <br />Czy chcesz zamienić na <br/><span id="newContent"></span>?</p>',
	_monit_IHasEmptyBasket: '<p>Usunąłeś towar z koszyka. Twój koszyk jest pusty.</p><p>To okno zniknie za kilka sekund...</p>',
	_monit_IHasPhoneAndWantAnotherPhone: '<p>W koszyku znajduje się już telefon <br/><span id="contentName"></span>.<br/>Czy chcesz zamienić go na inny w taryfie <br/><span id="newOffer"></span>?</p>',
	
    __confirmAction: function(a, actionArgs){
        switch(a){
            case 'abort': return function(){
                jQuery('#playboxClose').find('a').click();
				return false;
            };
            case 'change': return function(){ /* zamiana zawartości koszyka */
                _cMB.__log('U want change! I do change!');
				_cMB.__writeCookie(actionArgs);
				_cMB._basketFull = true;
				_cMB.genBasketHTML();
				return false;
            };
			case 'redirectToPhones': return function(){ /* przekierowanie na stronę telefonów zbiorczą */
				var tmpD = _cMB.getOfferData();
				jQuery('.pBC-OK').attr('href',_STRONA_ZBIORCZA_TELEFONY+'?oT='+_cMB._offerType+'&tA='+tmpD.tA.v+'&P='+tmpD.p.v);
			};
			case 'redirectToOffer': return function(){ /* przekierowanie na stronę oferty abonament */
				jQuery('.pBC-OK').attr('href',_STRONA_OFERTY_ABO);
			};
			case 'redirectToEshop': return function(){ /* przekierowanie do eshopa */
				var tmpD = _cMB.getOfferData();
				jQuery('.pBC-OK').attr('href', function(){ 
					var tmpCartUrl = prepareCartUrl(jQuery(this).parent().siblings('input[name=pID]').val(), tmpD.tA.v);
					_cMB.__log( tmpCartUrl );
					return tmpCartUrl;
				});
			};
            default: return false;
        };
    },
	__insertConfirm: function(c){
	    return '<div id="playboxConfirm" class="alignRight">' + ( c.cancel ? '<a class="linkPointer linkPointerBack pBC-Cancel" href="#" title="'+c.cancel.label+'"><span>'+c.cancel.label+'</span></a>' : '' ) + '&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;' + ( c.ok ? '<a class="ButtonBig pBC-OK" href="#" title="'+c.ok.label+'"><span>'+c.ok.label+'</span></a>' : '' ) + '</div>';
	},
    __showMonit: function(which,confirm){
        _cMB._monitShown = true;
        _cMB.playboxTrigger( '<div class="cartInfoLayer"><div class="cartMonit">' + eval('_cMB._monit_'+which) + ( confirm !== undefined ? _cMB.__insertConfirm(confirm) : '' ) + '</div></div>' );
		jQuery('#contentName').text(_cMB.getContentName( which=='IHasPhoneAndWantAnotherPhone'?false:true ));
		jQuery('#newContent').text( _cMB.NOW_ADDING == 'offer' ? 'wybraną ofertę' : 'wybrany telefon' );
		jQuery('#newOffer').text( jQuery('input[name=typAbonamentu]:checked').siblings('input[type=hidden]').val() );
		if( confirm !== undefined ){
			jQuery('.pBC-Cancel').click(_cMB.__confirmAction(confirm.cancel.action));
			jQuery('.pBC-OK').click(_cMB.__confirmAction(confirm.ok.action, confirm.ok.actionArgs));
        };
    }
    
};

_cMB.init();

/* obsługa koszyka - dodawanie */
/* zapamiętanie parametrów z geta jeśli jesteśmy na stronie pojedynczego telefonu (o ile takowe parametry są) - potrzebne dalej do przekazania info do eshopa i służy to jako zabezpieczenie, by nie zczytywać geta w momencie clicka w 'kup' */
if( jQuery('#product').length && jQuery('#product').find('a.cMB-singlePhone').length ){
	_getOT = _GET('oT');
	_getTA = _GET('tA');
	_getP = _GET('P');
};

var tmpPHref = '';
jQuery('#section').delegate('.cookieMonsterBasket','click',function(e){
	e.stopImmediatePropagation();
	var tmpForm = jQuery(this).parentsUntil('form').parent('form');
	/*tmpForm.submit(function(){ return false });*/
	var tmpContent = [];
	var tmpJSON = null;
	if( jQuery(this).hasClass('cMB-buyOffer') ){
	/* wybór oferty */
		_cMB._offerType = jQuery('input[name=offerType]').val();
		tmpForm.find('input:checked, select').each(function(){						
			/* zalozenie: w value inputa lub selecta siedzi id produktu */
			var tmpN = jQuery(this).attr('name');
			tmpJSON = JSON.parse('{"'+tmpN+'": { "v": "'+jQuery(this).val()+'", "d": "'+(this.tagName == 'INPUT' ? jQuery(this).siblings('input[type="hidden"]').val() : jQuery(this).find(':selected').text())+'"}}');
			tmpContent.push(tmpJSON);
		});
	}else if( jQuery(this).hasClass('cMB-buyOneProduct') ){
	/* wybór telefonu na stronie pojedynczego telefonu */
		var tmpName = jQuery('h1').text();
		var tmpPriceObj = jQuery(this).siblings('p.price').clone();
		var tmpPrice = tmpPriceObj.find('span').text().replace(/[^0-9\,\.]+/,'');
		var tmpPhoto = escape('<img src="'+jQuery(this).siblings('input[name=pIURL]').val()+'" alt="'+tmpName+'"/>');
		var tmpDetailsURL = jQuery(this).siblings('input[name=pDURL]').val();
		var tmpPID = jQuery(this).siblings('input[name=pID]').val();
		tmpJSON = JSON.parse('{"telefon":{"i":"'+tmpPhoto+'","d":"'+tmpName+'","u":"'+tmpDetailsURL+'","p":"'+tmpPrice+'","pid":"'+tmpPID+'"}}');
		tmpContent.push(tmpJSON);
	}else if( jQuery(this).hasClass('cMB-buyProduct') ){
	/* wybór produktu */		
		var newOT = jQuery('select[name=offer]').val();
		var newTA = jQuery('select[name=offerType]').val();
		var newPID = jQuery(this).parent().siblings('input[name=pID]').val();
		var newPROMO = jQuery('select[name=promotion]').val();
		/* sprawdzenie, czy oferta wybrana z dropdownów jest inna niż ta w ciachu (o ile mamy ciacho), jak mamy ciacho i jest inna to monit o zamianie */
		var cMBOD = _cMB.getOfferData();
		if( cMBOD ){
			//console.log( 'oT = 1 tA = ' + cMBOD.tA.v + ' wA = ' + cMBOD.wA.v + ' P = ' + cMBOD.p.v );
			//console.log( 'oT = ' + newOT +' tA = ' + newTA + ' wA = ' + cMBOD.wA.v + ' P = ' + newPROMO );
			_cMB.NOW_ADDING = 'offer';
			if( newOT != 1 || cMBOD.tA.v != newTA || cMBOD.p.v != newPROMO ){
				/* to co z dropów jest inne niż w ciachu -> poka monit -> na OK przekieruj do eShopa */
				_cMB.__showMonit('ICanHasANewBasket', {
					cancel: { label: 'Powrót', action: 'abort' },
					ok: { label: 'Zamień', action: 'redirectToEshop', actionArgs: 'oT='+newOT+'&aID='+newTA+'&pID='+newPID+'&promo='+newPROMO }
				});
				return false;
			};
		};
		/* przejście ze zbiorczej telefonów do koszyka na eshopie - przekazanie id abonamentu i id telefonu */
		if( tmpPHref == '' ){
			tmpPHref = '?oT=' + newOT + '&aID=' + newTA + '&pID=' + newPID + '&promo=' + newPROMO;
			jQuery(this).attr('href',function(){ return jQuery(this).attr('href') + tmpPHref; });
		}
		return true;
	}else if( jQuery(this).hasClass('cMB-singlePhone') ){
	/* kupno telefonu ze strony pojedynczego telefonu -> mamy już zapamiętaną ofertę (GET) więc idziemy do eshopu*/
		jQuery(this).attr('href',function(){ return jQuery(this).attr('href') + '?oT=' + _getOT + '&P=' +_getP + '&tA=' + _getTA + '&pID=' + jQuery('input[name=pID]').val(); });
		return true;
	};
	/* coś starego, ale niech na wszelki wypadek zostanie... */
	if( jQuery(this).hasClass('cMB-buyOfferWithProduct') ){
		return true;
	};
	if( jQuery(this).hasClass('cMB-buyOfferWithPhone') ){
	
	}
	/* offer - dowolna oferta, product - telefon czy cuś */
	_cMB.NOW_ADDING = jQuery(this).hasClass('cMB-buyOffer') ? 'offer' : 'product';
	_cMB.addToBasket(tmpContent, jQuery(this).hasClass('cMB-chooseOtherPhone')||jQuery(this).hasClass('cMB-chooseOtherOffer'), jQuery(this).hasClass('cMB-chooseOtherPhone'));
	
	return false;
});
function getPhoneFeatures(URL, getName, getPrice){
	jQuery.ajax({
		url: URL,
		dataType: 'html',
		success: function(d,t,x){
			var tmpF = jQuery(d).find('.phoneFeatures').html();
			jQuery('#phoneDetails').children('div').html(tmpF);
			if( getName ){
				var tmpN = jQuery(d).find('h1').text();
				jQuery('#phoneDetails').children('h4').html( tmpN );
				jQuery('#phoneDetailsImg').children('img').attr('title', tmpN);
			}
			if( getPrice ){
				jQuery('#phoneDetailsPrice').html( jQuery(d).find('#product .price span').html() ).next('p').remove();
			}
		}
	});
};
/* aktualizacja telefonu na stronie ofertowej - sekcja 'wybrany telefon' */
if( jQuery('.cMB-phoneDetails').length ){
	var tmpD = _cMB.getProductData();
	var tmpPDURL = _GET('pDURL');
	var tmpPIURL = _GET('pIURL');
	if( tmpD && tmpD !== undefined){
		jQuery('.cMB-phoneDetails').parent().addClass('promo').children('h3').html('Skompletuj ofertę do wybranego telefonu');
		jQuery('#phoneDetailsImg').html(unescape( tmpD.i ));
		jQuery('#phoneDetails').children('h4').text(tmpD.d);
		jQuery('#phoneDetailsPrice').html( tmpD.p + '<small>zł</small>').next('p').remove();
		getPhoneFeatures(tmpD.u, false, false);
		jQuery('#offerConfigSubmit').html('<a class="ButtonBig cMB-buyWithPhone" href="'+_STRONA_ESHOP_KOSZYK+'" title="Kup ofertę z tym telefonem"><span style="width:222px">Kup ofertę z tym telefonem</span></a><br/><a href="031_Telefony_zbiorcza.html" class="linkPointer cookieMonsterBasket cMB-buyOffer cMB-chooseOtherPhone" title="Dobierz inny telefon"><span>Dobierz inny telefon</span></a><br /><br /><a class="linkPointer" href="#" title="Kup ofertę bez telefonu"><span>Kup ofertę bez telefonu</span></a>');
	}else if( tmpPDURL != '' && tmpPIURL != '' ){
		/* wyświetlenie info o telefonie */
		jQuery('#offerConfigStep4').addClass('promo');
		getPhoneFeatures(tmpPDURL, true, true);
		jQuery('#phoneDetailsImg').children('img').attr({'src':decodeURIComponent(tmpPIURL)}).removeAttr('width').removeAttr('height');
		jQuery('#offerConfigSubmit').html('<a class="ButtonBig cMB-buyWithPhone" href="'+_STRONA_ESHOP_KOSZYK+'" title="Kup ofertę z tym telefonem"><span style="width:222px">Kup ofertę z tym telefonem</span></a><br/><a href="031_Telefony_zbiorcza.html" class="linkPointer cookieMonsterBasket cMB-buyOffer cMB-chooseOtherPhone" title="Dobierz inny telefon"><span>Dobierz inny telefon</span></a><br /><br /><a class="linkPointer" href="#" title="Kup ofertę bez telefonu"><span>Kup ofertę bez telefonu</span></a>');
	}
};
/* aktualizacja dropdownów na stronie zbiorczej telefonów */
if( jQuery('#searchOffer').length && jQuery('fieldset.searchOffer').length ){
	var tmpOT = _GET('oT');
	var tmpTA = _GET('tA');
	var tmpP = _GET('P');
	if( tmpOT && tmpTA && tmpP ){
		jQuery('select[name=offer]').val(tmpOT);
		jQuery('select[name=offerType]').val(tmpTA);
		jQuery('select[name=promotion]').val(tmpP);
	}
	jQuery('a.phoneDescription').click(function(e){
		e.stopImmediatePropagation();
		
		var tmpContent = [];
		
		_cMB._offerType = jQuery('select[name=offer]').val();
		jQuery('#searchOffer').find('select[name=offerType], select[name=promotion]').each(function(){						
			/* zalozenie: w value inputa lub selecta siedzi id produktu */
			var tmpN = jQuery(this).attr('name');
			tmpJSON = JSON.parse('{"'+tmpN+'": { "v": "'+jQuery(this).val()+'", "d": "'+ jQuery(this).find(':selected').text() +'"}}');
			tmpContent.push(tmpJSON);
		});
		
		_cMB.NOW_ADDING = 'product';
		_cMB.addToBasket(tmpContent, jQuery(this).hasClass('cMB-chooseOtherPhone')||jQuery(this).hasClass('cMB-chooseOtherOffer'), jQuery(this).hasClass('cMB-chooseOtherPhone'));
		
		/*var tmpParams = 'oT='+jQuery('select[name=offer]').val()+'&tA='+jQuery('select[name=offerType]').val()+'&P='+jQuery('select[name=promotion]').val();
		jQuery(this).attr('href',function(){
			return jQuery(this).attr('href')+'?'+tmpParams;
		});*/
		return false;
	});
	
};

/* ze str. ofertowej bezterminalowej przejście do eshopa */
jQuery('.ButtonBig.toEshop').click(function(){
	var tmpParams = '?oT=1';
	var tmpForm = jQuery(this).parent().parent('form');
	tmpForm.find('input:checked, select').each(function(i){
		var tmpN = '';
		switch(jQuery(this).attr('name')){
			case 'wysokoscAbonamentu': tmpN = 'wA'; break;
			case 'typAbonamentu': tmpN = 'tA'; break;
			case 'choosePromo': tmpN = 'P'; break;
		}
		tmpParams += '&' + tmpN + '=' + jQuery(this).val();
	});
	jQuery(this).attr('href',function(){ return jQuery(this).attr('href') + tmpParams; });
	return true;
});
jQuery('.cMB-buyOfferWithPhone, .cMB-buyWithPhone, .cMB-buyOfferWithoutProduct').live('click', function(){
	var newOT = jQuery('input[type=hidden][name=offerType]').val();
	var newTA = jQuery('input[name=offer]:checked').val();
	var newPID =  jQuery(this).hasClass('cMB-buyOfferWithoutProduct')||jQuery('.productStep').is(':hidden') ? null : jQuery('input[name=pID]').val();
	var newPROMO = jQuery('[name=choosePromo]').val();
	var cMBOD = _cMB.getOfferData();
	if( cMBOD ){
		_cMB.NOW_ADDING = 'offer';
		if( newOT != jQuery('input[type=hidden][name=offerType]').val() || cMBOD.tA.v != newTA || cMBOD.p.v != newPROMO ){
			/* to co z dropów jest inne niż w ciachu -> poka monit -> na OK przekieruj do eShopa */
			_cMB.__showMonit('ICanHasANewBasket', {
				cancel: { label: 'Powrót', action: 'abort' },
				ok: { label: 'Zamień', action: 'redirectToEshop', actionArgs: 'oT='+newOT+'&aID='+newTA+ (newPID==null?'':'&pID='+newPID)+'&promo='+newPROMO }
			});
			return false;
		};
	};
	return false;
});


/* zmiana dropów ofertowych na zb. telefonów jeśli przyszliśmy z mixa */
if( jQuery('#searchOffer').length && jQuery('fieldset.searchOffer').length && _GET('oT') == 2 ){
	var tmpHTML1 = '<option value="tA1"'+(_GET('tA')=='tA1'?' selected="selected"':'')+'>10 zł</option><option value="tA2"'+(_GET('tA')=='tA2'?' selected="selected"':'')+'>30 zł</option><option value="tA3"'+(_GET('tA')=='tA3'?' selected="selected"':'')+'>50 zł</option><option value="tA4"'+(_GET('tA')=='tA4'?' selected="selected"':'')+'>80 zł</option>';
	var tmpHTML2 = '<option value="doladowania1"'+(_GET('P')=='doladowania1'?' selected="selected"':'')+'>30 doładowań</option><option value="doladowania2"'+(_GET('P')=='doladowania2'?' selected="selected"':'')+'>40 doładowań</option>';
	jQuery('select[name=offerType]').html(tmpHTML1).siblings('span.label').text('Wartość doładowania');
	jQuery('select[name=promotion]').html(tmpHTML2).siblings('span.label').text('Ilość doładowań');
};
