//Only want map generated once
var main_map_initialized = false;

$(document).ready(function() {
	$('.smi-tab').click(function() {
		//Open this tab
		open_tab(this);

		return false;
	});
	
	$('.smi-tabset .smi-tab').hover(function() {
		$(this).addClass('tab-interaction');
	}, function() {
		$(this).removeClass('tab-interaction');
	});
});
//Open a handed tab (jq), of the given tab name
function open_tab(tab)
{
	//Tab group
	var tab_group_name = tab.parentNode.parentNode.id;
	//Goal tab
	var tab_name = tab.title;
	close_all_tabs(tab_group_name);
	
	$(tab).parent().addClass("smi-active");
	$("#"+tab_name).show();

	//Some tabs have associated functions for maps
	if(tab_name == 'smi-tab-map')
	{
		if(main_map_initialized != true)
		{
			loadMap();
			main_map_initialized = true;
		}
	}
	else if(tab_name == "smi-tab-street-view")
	{
		//Show the sv object if you click that
		if(streetmap_initialized != true)
		{
			initialize_streetmap();
			streetmap_initialized = true;
		}
	}
	return true;
}
//Close all tabs in a given group
function close_all_tabs(group_name)
{
	var group = $("#"+group_name).children();//.each(function(){
	var tabs = $("#"+group_name+"_holder").children();//.each(function(){
	var group_len = group.length;
	var tabs_len = tabs.length;
	//Droped .each to speed up tabs on slower browsers..ello IE
	//Turn of headers
	for(var i = group_len; i--;)
	{
		$(group[i]).removeClass("smi-active");
	}
	//Hide all tabs
	for(var i = tabs_len; i--;)
	{
		//$(tabs[i]).hide();
		tabs[i].style.display = "none";
	}
	return true;
}


$(document).ready(function(){
	$('#sf_form').submit(function()
		    {
		        var values = {};
		        $('#sf_form INPUT').each(function(index, element)
		        {
		            values[element.name] = $(element).val();
		        });
		        
		        var is_valid = validate_friend_inputs(values);
		        
		        // Don't submit the form if there are any warnings
		        if( is_valid == false )
		        {
		            return false;
		        }
		        
		        values['action'] = 'send_to_friend';
		        $('#sf_loading').show();
		        $.post('/ajax_endpoint.php', values, function(data)
		        {
		            $('#sf_loading').hide();
		            if(data['errors'].length == 0)
		            {
		                $('#sf_thankyou').show();
		                setTimeout('tb_remove();', 5000);
		            }
		            else
		            {
		                $('#sf_errors').empty();
		                $('#sf_errors').append(sprintf("<strong>W twojej wiadomości wystąpiły błędy:</strong>"));
		                $('#sf_errors').append("<ol>");
		                for(var index = 0; index < data['errors'].length; index++)
		                    $('#sf_errors OL').append(sprintf("<li>%s</li>", data['errors'][index]));
		                $('#sf_errors').append("</ol>");
		                $('#sf_errors').slideDown();
		                Recaptcha.reload();
		            }
		        }, 'json');
		        
		        // Never let the browser submit the form normally.
		        return false;
		    });
	/* Header mini links js */
	$('#swf, #rta_link').hover(
		function () {
			$(this).css({'cursor': 'pointer', 'color': '#333', 'background': '#fff'});
            $(this).children('img:first').attr('src', str_replace('off', 'on', $(this).children('img:first').attr('src')));

		},
		function () {
			$(this).css({'color': '#525252', 'background': '#f7f7f7'});
            $(this).children('img:first').attr('src', str_replace('on', 'off', $(this).children('img:first').attr('src')));
		}
	);
    
	$('#saved-ad, #print-page').hover(
		function () {
			$(this).css({'cursor': 'pointer', 'color': '#333', 'background': '#fff'});
            $(this).children('a:first').css('color', '#333');
            $(this).children('img:first').attr('src', str_replace('off', 'on', $(this).children('img:first').attr('src')));

		},
		function () {
			$(this).css({'color': '#525252', 'background': '#f7f7f7'});
            $(this).children().css('color', '#525252');
            $(this).children('img:first').attr('src', str_replace('on', 'off', $(this).children('img:first').attr('src')));
		}
	).click(function() {
        window.location = $(this).children('a:first').attr('href');
    });

	$('#rta_link').click(
		function(){
			tb_show(null, rta_url, null);
		}
	);

	$('#contact_advertiser').click(function() {
		//Open contact tab and focus on form
		open_tab($("#smi-contact-link")[0]);

		smoothScroll('#smi-contact-link');
		$('#your_name').focus();

    }).hover(
        function() {
            $(this).css('cursor', 'pointer')
			$(this).attr('src', '/images/button_contact_on.png');
        },
        function() {
			$(this).attr('src', '/images/button_contact_off.png');
    });
	
	$('#apply_now').hover(
        function() {
            $(this).css('cursor', 'pointer')
			$(this).attr('src', 'http://c1.dmstatic.com/i/button_apply_now_on.png');
        },
        function() {
			$(this).attr('src', 'http://c2.dmstatic.com/i/button_apply_now_off.png');
    });

    
    /* Truncate description */
    var trimmed_desc_length = 200;
 /*   if ($('#description').html().indexOf('non-adtech-campaign') != -1)
    {
		//Something going off here, needas another look 20110415 JN 
		// trimmed_desc_length = 1700;
    }*/
    $(document).ready(function(){
	    $('#description').jTruncate({
	        length: 200,
	        minTrail: 0,
	        moreText: 'Więcej info... <img src="http://c2.dmstatic.com/i/sr_sort_desc.png" alt="Click for more...">',
	        lessText: 'Mniej info... <img src="http://c1.dmstatic.com/i/sr_sort_asc.png" alt="Click for more...">'
	    });
    });

	$('.truncate_more_link').hover(function() {
			$(this).css("color", "#FE7C00");
			$(this).css("cursor", "pointer");
		},
		function() {
			$(this).css("color", "#2B2AE8");
			$(this).css("cursor", "default");
		});
	
	/* Form handling javascript */

	$('#ad_reply_submit').click(
		function() {
		ajax_reply();
		}
	);

	//Make textarea behave in ie
	$('#your_message').focus(
		function(){
			if($(this).val() == 'Wpisz wiadomość...')
			{
				$(this).css("color", "black");
				$(this).val("");
			}
		}
	);
	$('#your_message').blur(
		function(){
			if($(this).val() == '' || $(this).val() == null)
			{
				$(this).css("color", "#666");
				$(this).val("Wpisz wiadomość...");
			}
		}
	);
	//Blur focus means grey/yellow bg toggle
	$('#your_name,#your_email,#your_phone,#your_message').focus(function() {
			$(this).css({background: '#ffc'});
	});
	$('#your_name,#your_email,#your_phone,#your_message').blur(function() {
		$(this).css({background: '#f7f7f7'});
		return false;
	});
    
	/* Street Viewset up, checks if sv is available, then show tab if it is */
    // need to check if not defined for ads with no maps.
    if( typeof hit_code !== 'undefined' && hit_code < 300)
    {
        svLatLng = new GLatLng(lat, lon);
        // Use Streetview Client object to find nearest camera.
        gStreetView.getNearestPanoramaLatLng(
        svLatLng,
        function(camera)
        {
            if(camera != null)
            {
                camera_found = true;
                $('#street-view-tab').show();
                $(window).unload(function(){
                    GUnload();
                });
            }
        }
        );
    }

	/* Button hover and click actions */
	$('#ad_reply_submit').hover(
			function () {
				$(this).css('cursor', 'pointer');
				$(this).attr('src', '/images/button_email_on.png');
			},
			function () {
				$(this).attr('src', '/images/button_email_off.png');
			}
	);

	$('#contact_negotiator').hover(
		function () {
			$(this).css('cursor', 'pointer');
			$(this).attr('src', 'http://c3.dmstatic.com/i/button_contact_now_on.png');
		},
		function () {
			$(this).attr('src', 'http://c0.dmstatic.com/i/button_contact_now_off.png');
		}
	).click(function() {
		//Open contacts tab and focus on form
		open_tab($("#smi-contact-link")[0]);
		smoothScroll('#smi-contact-link');
		$('#your_name').focus();
    });
	
	//Mouse over and clicks for the mini map on smi
	$('#smi-small-map').hover(
        function() { 
			$(this).css({'cursor': 'pointer'}); 
			$('#smi-enlarge-map div').css({'text-decoration': 'underline', 'text-decoration': 'underline'}); 
		},
        function() { 
			$('#smi-enlarge-map div').css('text-decoration', 'none'); 
		}
    ).click(function() {
		//Switch tab to the large map tab
		open_tab($("#smi-map-link")[0]);
		smoothScroll('#smi-map-link');
    });

	//Link by price goes to finance tab
	$('#finance-tab-link, #smi-finance-link2').click(function() {
		//Switch tab to the large map tab
		open_tab($("#smi-finance-link")[0]);
		smoothScroll('#smi-finance-link');
    });
	/* Map tabs for domestic ads */
	//if(ad_type.indexOf('international') == -1 )
	//{
		 // need to check if not defined for ads with no maps.
		$hit_code =1;
		 if( typeof hit_code !== 'undefined' && hit_code < 300)
		 {
				svLatLng = new GLatLng(lat, lon);
				// Use Streetview Client object to find nearest camera.
				gStreetView.getNearestPanoramaLatLng(
					svLatLng,
					function(camera)
					{
						if(camera != null)
						{
							camera_found = true;
							$('#smi-sv-link').css("display", "list-item");

							$(window).unload(function(){
								GUnload();
							});
						}
					}
				);
			}
	//}
    
    $('#smi-finance-link2').click(function() {
        $('#smi-finance-link').trigger('click');
    });

	
	/* Photo Browser */
	$('.pb_link').hover(
		function () {
			$(this).css({cursor: 'pointer', color: '#fe7c00'});
		},
		function () {
			$(this).css({color: '#2b2ae8'});
		}
	).click(function(){
		//Allow l/r keys to work
		pb_open = true;
		//tb_show(null,'#TB_inline?inlineId=photo_browser&width=665&height=627',null);
		return false;
	});

    $('.smi-gallery .smi-photo a.p1').click(function() {
		//Allow l/r keys to work
		pb_open = true;
		tb_show(null,'#TB_inline?inlineId=photo_browser&width=665&height=627',null);
    });
    $('.smi-gallery .smi-photo a.v1').click(function() {
			tb_show(null, vb_url, null);
    });
    $('.smi-gallery .smi-photo a.v2').click(function() {
			tb_show(null, vt_url, null);
    });
	
	$('#sts').hover(
		function () {
			$(this).css({cursor: 'pointer', color: '#fe7c00'});
		},
		function () {
			$(this).css({color: '#2b2ae8'});
		}
	);


	$('#sts').click(
		function(){
			tb_show(null, tips_url, null);
		}
	);
});

//Just pass the href link e.g #smi-contact-link for a smooth scrolling effect
function smoothScroll(destTag) 
{
   var destination = $(destTag).offset().top;
   $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-20}, 500 );
   return false;
}

var load_fired = false;

$(window).bind('load', function() {
	if(!load_fired)
	{
		//ie7
		if($.browser.msie && $.browser.version.substr(0,1) == 7)
		{
			var addressOffset = -2;
			var marginTopOffset = 30;
			var tweetOffset = 7;
		}
		// ie6
		else if($.browser.msie && $.browser.version.substr(0,1) == 6)
		{
			var addressOffset = 28;
			var marginTopOffset = 22;
			var tweetOffset = 16;
		}
		else
		{
			var addressOffset = 10;
			var marginTopOffset = 37;
			var tweetOffset = 2;
		}

		var height = $('#address_box').height() + addressOffset;
		
		var margin_top = Math.round(((height / 2) - marginTopOffset) / 2); 

		if (margin_top < 0)
		{
			margin_top = 0;
		}

		$('#socmed_buttons_smi').height(height);

		$('#fb_loader').css('margin-top', margin_top + 'px');
		if($.browser.msie && $.browser.version.substr(0,1) == 6)
		{
			$('#fb_loader').css('padding-bottom', '0px'); 
		}
		else
		{
			$('#fb_loader').css('padding-bottom', margin_top + 'px');
		}
		$('#tweet_button').css('margin-top', (margin_top-tweetOffset) + 'px'); 

		load_fired = true;
	}
	
});

function validate_friend_inputs(values)
{
    var error_count = 0;
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    // Validate names
    if(values['sf_yn'].length == 0)
    {
        error_count++;
        $('#sf_yn_label').addClass('warning');
    }
    else
    {
        $('#sf_yn_label').removeClass('warning');
    }
    if(values['sf_fn'].length == 0)
    {
        error_count++;
        $('#sf_fn_label').addClass('warning');
    }
    else
    {
        $('#sf_fn_label').removeClass('warning');
    }

    // Emails
    if (values['sf_ye'].match(re) === null)
    {
        error_count++;
        $('#sf_ye_label').addClass('warning');
    }
    else
    {
        $('#sf_ye_label').removeClass('warning');
    }
    if (values['sf_fe'].match(re) === null)
    {
        error_count++;
        $('#sf_fe_label').addClass('warning');
    }
    else
    {
        $('#sf_fe_label').removeClass('warning');
    }

    return (error_count == 0);
}

