/* FRONT */
function offerDeleteConfirmationFront(Id){
	if(confirm('Czy na pewno?')){
		window.location=baseUrl+'user/delete/offer/'+Id;
	}
}

/* show agency contact */
function showAgencyContact()
{
	var hiddenAgencyButton = document.getElementById('hiddenAgencyButton');
	if (hiddenAgencyButton)
		hiddenAgencyButton.style.display = 'none';
	var hiddenAgencyInfo = document.getElementById('hiddenAgencyInfo');
	if (hiddenAgencyInfo)
		hiddenAgencyInfo.style.display = 'block';
	var hiddenAgentInfo = document.getElementById('hiddenAgentInfo');
	if (hiddenAgentInfo)
		hiddenAgentInfo.style.display = 'block';	
}

/* show private contact */
function showPrivateContact()
{
	var hiddenPrivateButton = document.getElementById('hiddenPrivateButton');
	hiddenPrivateButton.style.display = 'none';
	var hiddenPrivateInfo = document.getElementById('hiddenPrivateInfo');
	hiddenPrivateInfo.style.display = 'block';
}

/* show quick register form*/
function showQuickRegisterForm()
{		
	if($('#registerPopUpMain').is(':hidden')){
	
		var register_form =  $('#quickRegisterForm');
		
		register_form.show();
		
		showBackground();
		
            $('#registerPopUpMainInside').html(register_form);
            $('#registerPopUpMain').css({"z-index":"9002"});
            $('#registerPopUpMain').css({"margin-top":"100px"});
            $('#registerPopUpMain').fadeIn('slow');
	}	
	
}

function hideQuickRegisterForm()
{
	$('#registerPopUpMain').hide();
	hideBackground();
}

function quickLoginSubmit(idVt)
{
	validate = true;
	
	//reset errors
	$('#quickLoginEmailError').html('');
    $('#quickLoginPassError').html('');
	
 	var ErrorMsg1 = 'Nieprawidłowy adres e-mail';
 	var ErrorMsg2 = 'Nieprawidłowe hasło';
	var ErrorMsg3 = 'Podane dane są nieprawidłowe';
	
	
	var Email = $('input[name=loginEmail]').val();
	var Pass = $('input[name=existingPassword]').val();
  
  	if(!Email.match(/[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+\.[a-zA-Z0-9._%-]{2,4}/g))
  	{
    	validate = false;
    	$('#quickLoginEmailError').html(ErrorMsg1);
  	}
  	
  	if(Pass.length < 1)
 	{
    	validate = false;
    	$('#quickLoginEmailError').html(ErrorMsg2);
  	}
	
	if (validate == true){
		var post_url = ajaxUrl+'json/user/login';
		$.post(post_url ,
				{
				loginEmail: $('#loginEmail').val() ,
				existingPassword: $('#existingPassword').val()
				}, function(data){
                                    
						if (jQuery.trim(data) == 'true'){
                              
      						hideQuickRegisterForm();
      						
      						if(idVt){
      							activateVt('flashcontent',idVt);
      						}
      						
				   		}else{
         						$('#quickLoginEmailError').html(ErrorMsg3);
         						
         				}

			 });
	}	
}

function quickRegisterSubmit(idVt)
{
	validate = true;
	
	//reset errors
	$('#quickRegisterEmailError').html('');
    $('#quickRegisterPassError').html('');
	
 	var ErrorMsg1 = 'Nieprawidłowy adres e-mail';
 	var ErrorMsg2 = 'Nieprawidłowe hasło';
	var ErrorMsg3 = 'Podane hasła nie są identyczne';
	var ErrorMsg4 = 'Podany adres email jest już zarejestrowny';
	
	
	var Email = $('input[name=registerEmail]').val();
	var Pass = $('input[name=registerPassword]').val(); 
  	var PassCheck = $('input[name=registerPasswordCheck]').val();
  
  	if(!Email.match(/[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+\.[a-zA-Z0-9._%-]{2,4}/g))
  	{
    	validate = false;
    	$('#quickRegisterEmailError').html(ErrorMsg1);
  	}
  	
  	if(Pass.length < 1 || PassCheck <1)
 	{
    	validate = false;
    	$('#quickRegisterPassError').html(ErrorMsg2);
  	}
	
	
	if(Pass !== PassCheck)
 	{
    	validate = false;
    	$('#quickRegisterPassError').html(ErrorMsg3);
  	}
	
	if (validate == true){
		var post_url = ajaxUrl+'json/user/register';
		$.post(post_url ,
				{
				registerEmail: $('#registerEmail').val() ,
				registerPassword: $('#registerPassword').val()
				}, function(data){
                                    
						if (jQuery.trim(data) == 'true'){
                              
      						hideQuickRegisterForm();
      						
      						if(idVt){
      							activateVt('flashcontent',idVt);
      						}
      						
				   		}else{
         						$('#quickRegisterEmailError').html(ErrorMsg4);
         						
         				}

			 });
	}	
	
	
}

/* cookie - viewed VV */
function setCookiesVV(prod_id)
{
        $.ajax({
          type: "POST",
          url: ajaxUrl + 'json/search/set-cookies-vv/id/' + prod_id  + '/',
          success: function() {
                location.href=href;
          }
        });
        return false;
}

/* credit rate */
function credit_rate(price)
{
	n = 360; //ilosc rat
	r = 0.038; //oprocentowanie nominalne - expander
	m = 12; //ilosc rat, kapitalizacji w okresie stopy procentowej
	q = 1+(r/m);
				
	rata = (price * Math.pow(q, n) * ((q-1)/((Math.pow(q, n)-1))));
	rata = Math.round(rata);
				
	if (rata == 0 || rata == NaN) {rata = "brak danych";}
				
   	return rata;
}

/* credit rate tooltip */

$(function() {
/*	$('#credittip').tooltip({
	track: true,
	delay: 0,
	showURL: false,
	fade: 250,
	extraClass: "credittip"
	});
*/
});

/* credit pop up div */

function createDiv(div_id) {
	
	var blanket = document.getElementById('blanket');
	blanket.style.display = 'block';
	
 	var divTag = document.getElementById(div_id);
 	divTag.style.display = 'block';
 	divTag.innerHTML = "<div style='float: right;'><a href='#1' onclick=hideCreditPopUp('CreditPopUpDiv');><b>X</b></a></div><div style='float: left; font-size: 10px; font-weight: bold; color: #013299; padding-left: 5px;'><b></b></div><div style='float: left;'><iframe width='295' height='465' scrolling='no' src='https://dbdoradcy.pl/domoklik/' frameborder='0'>Niestety Twoja przeglądarka nie obsługuje ramek</iframe></div>";

}
function blanket_size(popUpDivVar) {
	if (typeof window.innerWidth != 'undefined') {
		viewportheight = window.innerHeight;
	} else {
		viewportheight = document.documentElement.clientHeight;
	}
	if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
		blanket_height = viewportheight;
	} else {
		if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
			blanket_height = document.body.parentNode.clientHeight;
		} else {
			blanket_height = document.body.parentNode.scrollHeight;
		}
	}
	var blanket = document.getElementById('blanket');
	blanket.style.height = blanket_height + 'px';
	var popUpDiv = document.getElementById(popUpDivVar);
	//popUpDiv_height=blanket_height/2-150;//150 is half popup's height
	popUpDiv_height = 200;
	popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos(popUpDivVar) {
	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerHeight;
	} else {
		viewportwidth = document.documentElement.clientHeight;
	}
	if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
		window_width = viewportwidth;
	} else {
		if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
			window_width = document.body.parentNode.clientWidth;
		} else {
			window_width = document.body.parentNode.scrollWidth;
		}
	}
	var popUpDiv = document.getElementById(popUpDivVar);
	window_width=window_width/2-204;//150 is half popup's width
	popUpDiv.style.left = window_width + 'px';
}
function showCreditPopUp(windowname) {
	
	createDiv(windowname);
	blanket_size(windowname);
	window_pos(windowname);
		
}
function hideCreditPopUp(windowname) {
	
	var el = document.getElementById(windowname);
 	el.style.display = 'none';
	var blanket = document.getElementById('blanket');
	blanket.style.display = 'none';

}

function setCookiesToBack(prod_id, href )
{
   var link = $("#searchListLinkToPageInput").val();
        $.ajax({
                  type: "POST",
                  url: ajaxUrl + 'json/search/set-cookies/id/' + prod_id + '?link=' + encodeURIComponent(link),
                  success: function() {
                        location.href=href;
                  }
                });
                return false;
}

function goBackToSearch(){
    if(BackToSearchSwitch){
        $('body').hide();
        location.href=BackToSearch; return false;
    }
}

function handler(newHash, initial) {
    if (initial)
        alert('Hash is "' + newHash + '"');
    else
        alert('Hash changed to "' + newHash + '"');
}

function prepareHash() {
	if (typeof(BackToSearchSwitch) != 'undefined' && BackToSearchSwitch) {
		$(window).load(function () {
			setTimeout("window.location.hash = '1'; DoHashCheck = true;", 100);
	        setInterval("checkHash()", 100);
		});
	}
}

function checkHash(){
//alert(window.location.hash);
    if(window.location.hash != '#1' && DoHashCheck){
        DoHashCheck = false;
        goBackToSearch();
    }
}

function provideMinMaxSearchInput(){
    
   // min-max numbers only
   $(".offerSearchCrit").keyup(function () { 
    	this.value = this.value.replace(/[^0-9\.]/g,'');
   });
      
   // min-max swap
   swapValue = [];
   $(".offerSearchCrit").each(function(i){

		swapValue[i] = $(this).val();

      	$(this).focus(function(){
      		if ($(this).val() == swapValue[i]) {
      		$(this).val("");
      		$(this).css({color:'#757575'});
      		}
      	$(this).addClass("focus");
		}).blur(function(){
      		if ($.trim($(this).val()) == "") {
      		$(this).val(swapValue[i]);
			$(this).css({color:'#000000'});
      		$(this).removeClass("focus");
     	 	}
  	});				
			
   	});    
    
}


$(document).ready(function(){
    prepareHash();
    insertGoogleMap();
    
	//leads_financial click
	$('#offerContactSubmitButt').click(function() {	
		
		if ($('#financial_offer:checked').val() !== undefined) {
			finalcial_url = 'http://tracking.quisma.com/c.cfs?pid=61344673620S1149298T&gkid=PMQ524d27278af29b1';
			window.open(finalcial_url);
			//return false;
		}
		
 	});

	/*ab: nie dziala nie wiem dlaczego (?)
 	*if(jQuery.browser.opera){
  		opera.setOverrideHistoryNavigationMode('compatible');
  		alert(opera.getOverrideHistoryNavigationMode());
    }*/

    if(isDefined('DirectHit')){
        if(DirectHit != true){
            //loadListSearchResults(CurrentPage, IdOrder);
        }
    }
    
    provideMinMaxSearchInput();

    /* contact form */

    // values swap
    swapValues = [];
    $(".offerZapytajInput").each(function(i){

		$(this).attr('autocomplete', 'off');

	    swapValues[i] = $(this).val();
	
	    $(this).focus(function(){
	    if ($(this).val() == swapValues[i] && ($(this).val() == 'Imię i nazwisko' || $(this).val() == 'Name & Surname' || $(this).val() == 'Adres e-mail' || $(this).val() == 'Adres e-mail (wymagany)' || $(this).val() == 'Email (required)' || $(this).val() == 'Numer telefonu (wymagany)') || $(this).val() == 'Numer telefonu(wymagany)' || $(this).val() == 'Phone number(required)' || $(this).val() == 'Phone number') {
	            $(this).val("");
	            $(this).css({color:'#000000'});
	    }
	    $(this).addClass("focus");
	    }).blur(function(){
	    if ($.trim($(this).val()) == "" && (swapValues[i] == 'Imię i Nazwisko' || swapValues[i] == 'Name & Surname' || swapValues[i] == 'Adres e-mail' || swapValues[i]  == 'Email (required)' || swapValues[i] == 'Numer telefonu') || swapValues[i] == 'Numer telefonu(wymagany)' || swapValues[i] == 'Phone number(required)' ) {
	            $(this).val(swapValues[i]);
	            $(this).css({color:'#757575'});
	            $(this).removeClass("focus");
	      }
	    });

    });

});

/* ***************************    Lista listy wyszukiwania w widoku ofety*/

function loadListSearchResults(Page, IdOrder){
var Link = SearchResultsLinkShort +'page'+'/'+Page+'/';
$('#searchListResultArea').addClass('mapOpacity');
    $.ajax({
        url: ajaxUrl + 'json/search/get-offer-view-list',
        type: 'POST',
        data: "idOrder="+IdOrder+"&link="+encodeURIComponent(Link),
        success: function(result) {
                Data = json_parse(result);
                $('#searchListResultArea').html(Data);
                $('#searchListResultArea').removeClass('mapOpacity');
                CurrentPage = Page;
        }
    });

}


/* zegarek i data przy zapytaniu o oferte*/

OfferDateCalendarStartDay = 0;
OfferDateCalendarStartMonth = 0;
OfferDateCalendarStartYear = 0;
function offerDateWeek(Type){
    switch(Type){
        case 'prev':
            OfferDateCalendarStartDay -= 7;
            offerDateShow(OfferDateCalendarStartDay, OfferDateCalendarStartMonth, OfferDateCalendarStartYear);
        break;
        case 'next':
            OfferDateCalendarStartDay += 7;
            offerDateShow(OfferDateCalendarStartDay, OfferDateCalendarStartMonth, OfferDateCalendarStartYear);
        break;
    }
}

function offerDateShow(StartDay, StartMonth, StartYear){
    var DateTime = new Date();
    var CurrDay = DateTime.getDate();
    var CurrMonth = DateTime.getMonth()+1;
    var CurrYear = DateTime.getFullYear();
    if(!OfferDateCalendarStartDay > 0){
        OfferDateCalendarStartDay = CurrDay;
    }
    if(!OfferDateCalendarStartMonth > 0){
        OfferDateCalendarStartMonth = CurrMonth;
    }
    if(!OfferDateCalendarStartYear > 0){
        OfferDateCalendarStartYear = CurrYear;
    }
    
    if(!StartDay > 0){
        StartDay = CurrDay;
    }
    if(!StartMonth > 0){
        StartMonth = CurrMonth;
    }
    if(!StartYear > 0){
        StartYear = CurrYear;
    }
    // jeżeli day < 0 to przeskakujemy do poprzedniego miesiąca
    if(StartDay < 0){
        OfferDateCalendarStartMonth -= 1;
        StartMonth = OfferDateCalendarStartMonth;
        var DaysInPrevMonth = daysInMonth(OfferDateCalendarStartMonth, OfferDateCalendarStartYear);
        OfferDateCalendarStartDay = DaysInPrevMonth + StartDay;
        StartDay = OfferDateCalendarStartDay;
    }
    //jeżeli miesiąc jest mniejszy od 0 to przeskakujemy do poprzedniego roku
    if(StartMonth <= 0){
        StartMonth = OfferDateCalendarStartMonth = 12;
        OfferDateCalendarStartYear -= 1;
        StartYear = OfferDateCalendarStartYear;
    }
    //jeżeli dzień jest mniejszy od dzisiejszej daty to przestawiamy na dzisiejszą datę
    if((StartMonth < CurrMonth && CurrYear == StartYear) || (StartMonth == CurrMonth && CurrYear == StartYear && StartDay < CurrDay)){
       OfferDateCalendarStartMonth = StartMonth = CurrMonth;
       OfferDateCalendarStartDay = StartDay = CurrDay;
    }
    var DaysInMonth = daysInMonth(StartMonth, OfferDateCalendarStartYear);
    var Res = new Array;
    var Day = 0;
    var MonthUp = true;
    for(I = StartDay; I < StartDay+7; I++){
        var ItemArr = new Array;
        Day = I;
        if(Day > DaysInMonth){
            Day -= DaysInMonth;
            if(MonthUp){
                OfferDateCalendarStartMonth += 1;
                OfferDateCalendarStartDay -= DaysInMonth;
                MonthUp = false;
                //jeżeli miesiąc > od 12 przeskakujemy do nastęnego roku
                if(OfferDateCalendarStartMonth > 12){
                    OfferDateCalendarStartMonth = OfferDateCalendarStartMonth - 12;
                    OfferDateCalendarStartYear += 1;
                }
            }
        }
        var DayOfWeek = new Date(OfferDateCalendarStartYear, OfferDateCalendarStartMonth-1, Day).getDay();
        //ItemArr['name'] = monthNameFromId(StartMonth)+'<br />'+dayNameFromId(DayOfWeek, 'shortName')+'<br />'+Day;
        var lng = 'pl';
       // if(lang == '_en') lng = 'en';
        
        if(lang == '_en' || lang == 'en') lng = 'en';
        if(lang == '_pl' || lang == 'pl') lng = 'pl';
        
        ItemArr['name'] = dayNameFromId(DayOfWeek, 'shortName', lng)+ '<br />' + Day;
        ItemArr['day'] = Day;
        ItemArr['year'] = OfferDateCalendarStartYear;
        ItemArr['month'] =  monthNameFromId(StartMonth, lng);
        ItemArr['monthId'] =  StartMonth;
       Res.push(ItemArr);
    }
    offerDateAreaFill(Res);
}

function offerDateAreaFill(Content){
    var Con = '';
    var Item = '';
    for(var I in Content){
        Item = Content[I];
        //name = Item['name'].replace('<br />', '') ;
        day =  Item['day'];
        month =  Item['month'];
        year = Item['year'];
        monthId = Item['monthId'];
        
		
        Con += '<div class="l day_field" onclick="showSelectedDate('+day+','+monthId+','+year+');return false;">'+Item['name'] + '</div>';
    }
    $('#offerDateAreaContent').html(Con);
}

function offerDateHourShow(Hour, Minute){
    var UseHour = Hour == -1 ? false : true;
    var UseMinute = Minute == -1 ? false : true;
    if(UseHour){
        if(Hour > 22){
            Hour = 6;
        }
        if(Hour < 6){
            Hour = 22;
        }
    }
    if(UseMinute){
        if(Minute >= 60 || Minute == 0){
            Minute = '00';
        }
        if(Minute < 0){
            Minute = 45;
        }
    }
    offerDateHourFill(Hour, Minute);
}

function showSelectedHour(){
	    hour_arrange = $('#offerDateHourArea').text() + ':' + $('#offerDateMinuteArea').text();
	 	$('#arrange_hour').val(hour_arrange);
	 	//$('#hour_minute').html('Proponowana godzina spotkania'+hour_arrange);
}
function offerDateHourUp(){
    var Hour = offerDateHourGet();
    offerDateHourShow(Hour+1, -1);
    showSelectedHour();
}
function offerDateHourDown(){
    var Hour = offerDateHourGet();
    offerDateHourShow(Hour-1, -1);
    showSelectedHour();
}
function offerDateMinuteUp(){
    var Minute = offerDateMinuteGet();
    offerDateHourShow(-1, Minute+15);
    showSelectedHour();
}
function offerDateMinuteDown(){
    var Minute = offerDateMinuteGet();
    offerDateHourShow(-1, Minute-15);
    showSelectedHour();
}

OfferDateHour = 18;
OfferDateMinute = 30;

function offerDateHourGet(){
    return parseInt(OfferDateHour);
}
function offerDateMinuteGet(){
    return parseInt(OfferDateMinute);
}

function offerDateHourFill(Hour, Minute){
    if(Hour != -1){
        $('#offerDateHourArea').html(Hour);
        OfferDateHour = Hour;
    }
    if(Minute != -1){
        $('#offerDateMinuteArea').html(Minute);
        OfferDateMinute = Minute;
    }
}
function showSelectedDate( day,monthId,year ){

        var agrement = $('#agreement').is(':checked');
	
	if ( agrement == true ){
		var month = monthId;
		$('#arrange_date').val(day+'-'+monthId+'-'+year);
		if ( monthId > 0 && monthId < 10) month = '0'+monthId;
		
		
		//day = day.replace(',', '-') ;
		
		$('#offerDateAreaContent').hide();
		$('#prev_date').hide();
		$('#next_date').hide();
		$('#cal').hide();
		var msg = '';
		var prop_date = day+'-'+month+'-'+year;
		if(lang == 'pl'){
			 msg  = 'Proponowana data spotkania '+prop_date;
		}else if(lang == 'en'){
	         msg  = 'Propose time for visiting '+prop_date;
		}
		
		$('#arrange_date_proposition').html(msg);
		$('#arrange_date_proposition').show();
	}
}

function insertGoogleMap(){
    if(isDefined('AddGoogleMap') && AddGoogleMap && GBrowserIsCompatible()){
        mapa = new GMap2(document.getElementById("offerMap"));
        mapa.addControl(new GLargeMapControl());

        scale = 13;

        Icon = new GIcon();
        Icon.shadow = layoutUrl+"images/ico/gmap/home.png";
        Icon.iconSize = new GSize(24, 24);
        Icon.shadowSize = new GSize(24,24);
        Icon.iconAnchor = new GPoint(24,24);
        //Icon.infoWindowAnchor = new GPoint(5, 1);

        if(latitude > 0 && longitude > 0){
            
            var point = new GLatLng(latitude, longitude);
            var marker = new GMarker(point, Icon);
            
            mapa.setCenter(new GLatLng(latitude,longitude),scale);
            mapa.addOverlay(marker);
            
        }else if(GoogleMapAdress!=''){
            
            var geo = new GClientGeocoder();
            var coordinates=new Array()
            
            geo.getLocations(GoogleMapAdress, function(wyniki){
            if (wyniki != 'undefined'){
                latitude = wyniki.Placemark[0].Point.coordinates[1];
                longitude = wyniki.Placemark[0].Point.coordinates[0];
                var point = new GLatLng(latitude, longitude);
                var marker = new GMarker(point, Icon);
                mapa.setCenter(new GLatLng(latitude,longitude),scale);
                mapa.addOverlay(marker);
            }
            });
       }else{
            mapa(52.22850915305482, 21.021738052368164, 13);
       }
    }
}


