/*
	@modified: 23.05.2011 14:59
*/

if( typeof jQuery == 'undefined' ){}
else
{
	var FILTER_MATERJAL_STR = 'Hoovelliist-filter-materjal',
		MATERJALID_IDD = [],
		FILTER_RESULTS_PER_PAGE = 15,
		prettyPhoto_options = {
			animationSpeed: 'normal',
			opacity: 0.35,
			showTitle: true,
			allowresize: true,
			default_width: 500,
			default_height: 344,
			counter_separator_label: '/',
			theme: 'facebook',
			hideflash: false,
			wmode: 'opaque',
			autoplay: false,
			modal: false,
			social_tools: false,
			deeplinking: false
		};

	$(document).ready(function(){
		/* pop-up aken */
		$('a[rel="popup"]').click(function(){
			uus_popup_aken(this.href);
			return false;
		});

		$('#popup-win-close').click(function(){
			$('.prev-product, .next-product').hide();
			$('#popup-win-back').removeAttr('class').hide();
		});

		if( typeof $().prettyPhoto != 'undefined' ){
			$("a[rel^=prettyPhoto], a[rel^=lightbox]").prettyPhoto(prettyPhoto_options);
		}

		if( $('#main-page-news').length > 0 ){
			$('#main-page-news li .p2is').click(function(){
				$('#main-page-news .sisu').each(function(){
					$(this).hide().prev().show();
				});

				$(this).hide().next().show();
			});

			$($('#main-page-news li .p2is')[0]).trigger('click');
		}

		if( $('#products-list').length > 0 ){
			$().check_filters();
		}


		if( $('.scroll-pane').length > 0 ){
			$.getScript(kodulehe_aadress + 'js/jquery.mousewheel.js', function(){
				$.getScript(kodulehe_aadress + 'js/jquery.jscrollpane.min.js', function(){
					$('.scroll-pane').jScrollPane({
						showArrows: true,
						verticalArrowPositions: 'split',
						horizontalArrowPositions: 'split'
					});
				});
			});
		}
	});/* END of $(document).ready({});*/

	$(window).load(function(){
		/* prettyphoto, lightbox */
		$('#main-menu li').css('cursor', 'pointer').hover(function(){
			var n=$(this).children('ul');
			
			if( $(n).length > 0 ){
				var npadt=$(n).css('padding-top'),
				npadb=$(n).css('padding-bottom'),
				nh=$(n).height(),
				eh = '-' + parseInt(nh + parseInt(npadt) + parseInt(npadb) - 3) + 'px';

				if( $(n).css('margin-top') === eh ){
				} else {
					$(n).css({'margin-top':eh})
				}

				if( typeof npadt === 'undefined' || typeof npadb === 'undefined' || nh === null ){}
				else {
					$(n).stop(true, true).delay(300).slideDown(400);
				}
			}
		}, function(){
			var n = $(this).children('ul');

			if( $(n).length > 0 ){
				$(n).stop(true, true).slideUp(700);
			}
		});

		/* tooted */
		if( $('#products-list').length > 0 ){

			$().getProductPageContents(); // käivitame selle koheselt kui leht on ära laetud

			$('#show-all-products').click(function(e){
				e.preventDefault();

				$.cookie(FILTER_MATERJAL_STR, null);

				$('#products-options ul li a').each(function(){
					$(this).removeClass('valitud');
				});

				$('.toode').each(function(){
					$(this).show();
				});
			});



			$('#products-options a').live('click', function(e){
				var c = 0, kas_voib_peita = true, opt_id = $(this).attr('href').replace('#', '');

				e.preventDefault();

				$('.toode').hide();

				var opt_valikud = [];

				var idd = [];

				if( $(this).hasClass('valitud') ){
					$(this).removeClass('valitud');
					kas_voib_peita = false;
				} else {
					$('#products-options a').removeClass('valitud'); // @added: 1.06.2011 - eemaldame mitme valiku võimalused
					$(this).addClass('valitud');

					self_id = $(this).attr('href').replace('#', '');

					if( jQuery.inArray(parseInt(self_id), idd) == 1 ){
						idd.push( parseInt(self_id) );
					}

					if( jQuery.inArray(self_id, opt_valikud) == -1 ){
						opt_valikud.push(self_id);
					}
				}

				/*
				// @delete: 1.06.2011 - kuna nüüd oli vaja ainult ühte filtri valikut
				var idd = [];
				$('#products-options a').each(function(){
					if( $(this).hasClass('valitud') ){
						++c;

						self_id = $(this).attr('href').replace('#', '');

						if( jQuery.inArray(parseInt(self_id), idd) == -1 ){
							idd.push( parseInt(self_id) );
						}

						if( jQuery.inArray(self_id, opt_valikud) == -1 ){
							opt_valikud.push(self_id);
						}
					}
				});
				*/

				$().getProductPageContents();
			});


			$('#page-numbers a').live('click', function(e){
				e.preventDefault();

				$('#page-numbers a.valitud').removeClass('valitud');
				$(this).addClass('valitud');

				$().getProductPageContents();
			});

			$('#popup-win-content .prev-product, #popup-win-content .next-product').live('click', function(e){
				e.preventDefault();

				var c = $('#popup-win-back').attr('class'), 
					ex = c.split('__'), 
					r, 
					sel_opts = [];

				$('#products-options a.valitud').each(function(){
					sel_opts.push( $(this).attr('href').replace('#', '') );
				});

				var sel_opts_len = sel_opts.length;

				if( $(this).hasClass('prev-product') ){
					r = $($('#products-list a#' + ex[0]).prevAll(':visible')[0]);
					if( r.length > 0 ) $(r).trigger('click');
				} else {

					r = $($('#products-list a#' + ex[0]).nextAll(':visible')[0]);
					if( r.length > 0 ) $(r).trigger('click');
				}


			});

			$('.toode').click(function(e){
				e.preventDefault();

				var data = $(this).children('span.hidden-data').text();
				if( data ){
					var ex = data.split('|'),
						row = '',
						prev_elem = $($(this).prevAll('a:visible')[0]),
						next_elem = $($(this).nextAll('a:visible')[0]),
						valitud_filtri_v22rtus = $(this).attr('class').replace('toode sort-materjal__', '');

					if( typeof prev_elem == 'undefined' ) prev_elem = [];
					if( typeof next_elem == 'undefined' ) next_elem = [];

					if( prev_elem.length > 0 || next_elem.length > 0 ){
						$('#popup-win-close').trigger('click');
					}

					if( prev_elem.length > 0 ){
						//row += '<div class="prev-product"><a href="javascript:void(0);"><span>prev<\/span><\/a><\/div>';
						$('.prev-product').show();
					}

					if( next_elem.length > 0 ){
						//row += '<div class="next-product"><a href="javascript:void(0);"><span>next<\/span><\/a><\/div>';
						$('.next-product').show();
					}

					if( ex.length > 0 ){
						var pilt = ex[2],
							ex2 = (typeof ex[4] != 'undefined' ? ex[4].split(';') : false);

						if( ex[3].length > 0 ){
							row += '<a href="' + ex[3] + '" rel="prettyPhoto" class="product-img"><img src="' + ex[2] + '" alt="' + ex[1] + '" /><\/a>';
						} else {
							row += '<img src="' + ex[2] + '" alt="' + ex[1] + '" class="product-img" />';
						}

						if( ex2.length > 0 ){
							row += '<ul>';

							for(i=0;i<ex2.length;i++){
								row += '<li>' + ex2[i] + '</li>';
							}

							row += '</ul>';
						}
					}

					//$('#popup-win-content').empty().append(row);
					$('#popup-win-content-data').empty().append(row);
					$('#popup-win-back').attr('class', $(this).attr('id') + '__' + valitud_filtri_v22rtus).show();
				}

				return false;
			});

			$('#popup-win-content a.product-img').live('click', function(e){
				e.preventDefault();

				var img = $(this).children('img'),
					img_pic = $(this).attr('href'),
					img_title = $(img).attr('alt'),
					img_desc = $(img).attr('longdesc');

				$.fn.prettyPhoto(prettyPhoto_options);
				$.prettyPhoto.open(img_pic, (typeof img_title != 'undefined' && img_title.length>0 ? img_title : ' '), (typeof img_desc != 'undefined' && img_desc.length>0 ? img_desc : ' '));
			});
		}


		if( $('#kontaktinfo_riba').length > 0 )
		{
			$('#kontaktinfo_riba img').imgEmail2Link();
		}

		if( $('.meeskonna-liikme-email').length > 0 )
		{
			$('.meeskonna-liikme-email img').imgEmail2Link();
		}
	});

	jQuery.fn.extend({
		imgEmail2Link: function(){
			$(this).each(function(){
				$(this).wrap('<a href="mailto:' + $(this).attr('alt') + '" />');
			});
		},

		getProductPageContents: function(){
			var items = $('#products-list a.toode'), 
				items_len = items.length,
				product_options = $('#products-options a.valitud');

			$(items).hide();

			var p_opt = [];
			if( product_options.length > 0 ){
				$(product_options).each(function(){
					item_id = $(this).attr('href').replace('#', '');

					if( jQuery.inArray(item_id, p_opt) == -1 ){
						p_opt.push( parseInt(item_id) );
					}
				});
			}

			var show_items = [],
				p_opt_len = p_opt.length;

			$(items).each(function(){
				class_ids = $(this).attr('class');
				class_ids_ex = class_ids.split(' ');
				item_id = $(this).attr('id');

				if( p_opt_len > 0 ){
					if( typeof class_ids_ex[1] != 'undefined' 
						&& class_ids_ex[1].indexOf('sort-materjal__') != -1 
					){
						klass = class_ids_ex[1].replace('sort-materjal__', '');
						klass_ex = klass.split('-');

						for(i=0;i<p_opt_len;i++){
							if( jQuery.inArray( p_opt[i].toString(), klass_ex ) != -1 ){
								if( jQuery.inArray(item_id, show_items) == -1 ){
									show_items.push(item_id);
								}
							}
						}
					}
				} else {
					if( jQuery.inArray(item_id, show_items) == -1 ){
						show_items.push(item_id);
					}
				}
			});

			if( show_items.length > 0 ){
				var k = 0,
					m = 0,
					per_page = FILTER_RESULTS_PER_PAGE,
					show_items_len = show_items.length;

				$().genProductPageNumBar(show_items_len);

				for(j=0;j<show_items_len;j++){
					if(k===0){
						m++;
					}

					k++;

					if( k<=per_page ){
						if( m === parseInt( $('#page-numbers a.valitud').text() ) ){
							$('#' + show_items[j]).show();
						}
					}

					if(k===per_page) k=0;
				}
			}
		},

		genProductPageNumBar: function(items){
			var per_page = FILTER_RESULTS_PER_PAGE,
				pages = parseFloat(Math.round(items/per_page)),
				last_page = Math.ceil(items/per_page),
				page_numbers_html = '',
				placeholder = $('#page-numbers'),
				page_selected_num = $('#page-numbers a.valitud').text(),
				page_selected_rel = $('#page-numbers a.valitud').attr('rel'),
				page_selected = parseFloat(page_selected_num != '' ? page_selected_num : 1);

			if( pages == 0 ) pages = 1;

			if( pages > 0 && (pages < page_selected) ){
				page_selected = 1;
			}

			if( pages > 0 ){
				page_numbers_html = '<ul>';

				for(i=1;i<=pages;i++){
					page_numbers_html += '<li>' + 
						'<a href="javascript:void(0);"' + (page_selected == i ? ' class="valitud"': '') + ' rel="num-' + i + '">' + i + '<\/a>' + '<\/li>';
				}

				page_numbers_html += '</ul>';

				$(placeholder).empty().append(page_numbers_html);
			} else {
				$(placeholder).empty();
			}
		},

		check_filters: function(){
			var cookie_data = $.cookie(FILTER_MATERJAL_STR);

			if( cookie_data && cookie_data != null ){
				var ex2 = cookie_data.split(';'),
					ex2_len = ex2.length;

				$('#products-options ul li a').each(function(){
					for(i=0;i<ex2_len;i++){
						if( $(this).attr('href').indexOf(ex2[i]) != -1 ){
							$(this).addClass('valitud');
						}
					}
				});

				$('.toode').each(function(){
					var klass = $(this).attr('class'),
						self = $(this),
						ex = klass.split(' ');

					if( klass.indexOf('sort-materjal__') != -1 ){
						if( ex.length > 0 ){
							if( typeof ex[1] != 'undefined' ){
								str = ex[1].replace('sort_materjal__', '');
								$(self).hide();

								for(i=0;i<ex2_len;i++){
									if( str.indexOf(ex2[i]) != -1 ){
										$(self).show();
									}
								}
							}
						}
					} else {
						if( $(this).is(':visible') ){
							$(this).hide();
						}
					}
				});
			} else {
				$('.toode').show();
			}
		},

		check_filter: function(a){
			$('.toode').each(function(){
				var klass = $(this).attr('class'),
					self = $(this),
					ex = klass.split(' ');

				if( klass.indexOf('sort-materjal__') != -1 ){
					if( ex.length > 0 ){
						if( typeof ex[1] != 'undefined' ){
							if( typeof a === 'boolean' ){
								$(self).show();
							} else {
								str = ex[1].replace('sort-materjal__', '');
								$(self).hide();

								ex2 = a.split(';');
								for(i=0;i<ex2.length;i++){
									if( str.indexOf(ex2[i]) != -1 ){
										$(self).show();
									}
								}
							}
						}
					}
				} else {
					if( $(this).is(':visible') ){
						$(this).hide();
					}
				}
			});
		},

		getPrettyPhotoEffect: function(){
			if( $('a[rel^=prettyphoto], a[rel^=lightbox]').length > 0 ){
				$('<link>').appendTo('head').attr({
					rel: 'stylesheet', 
					type: 'text/css', 
					href: kodulehe_aadress  + 'kujundused/iitee/assets/css/prettyPhoto.css'
				});

				$.getScript(kodulehe_aadress + 'js/jquery.prettyPhoto.js', function(){
					$().getPrettyPhotoBox();
				});
			}
		},

		getPrettyPhotoBox: function(){
			$("a[rel^=prettyPhoto], a[rel^=lightbox]").prettyPhoto({
				animationSpeed: 'normal', /* fast/slow/normal */
				opacity: 0.35, /* Value between 0 and 1 */
				showTitle: true, /* true/false */
				allowresize: true, /* true/false */
				default_width: 500,
				default_height: 344,
				counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
				theme: 'facebook', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
				hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
				wmode: 'opaque', /* Set the flash wmode attribute */
				autoplay: false, /* Automatically start videos: True/False */
				modal: false, /* If set to true, only the close button will close the window */
				changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
				callback: function(){}, /* Called when prettyPhoto is closed */
				markup: '<div class="pp_pic_holder"> \
							<div class="pp_top"> \
								<div class="pp_left"></div> \
								<div class="pp_middle"></div> \
								<div class="pp_right"></div> \
							</div> \
							<div class="pp_content_container"> \
								<div class="pp_left"> \
								<div class="pp_right"> \
									<div class="pp_content"> \
										<div class="pp_fade"> \
											<a href="#" class="pp_expand" title="Expand the image">Expand</a> \
											<div class="pp_loaderIcon"></div> \
											<div class="pp_hoverContainer"> \
												<a class="pp_next" href="javascript:void(0);">next</a> \
												<a class="pp_previous" href="javascript:void(0);">previous</a> \
											</div> \
											<div id="pp_full_res"></div> \
											<div class="pp_details clearfix"> \
												<a class="pp_close" href="#">Close</a> \
												<p class="pp_description"></p> \
												<div class="pp_nav"> \
													<a href="javascript:void(0);" class="pp_arrow_previous">Previous</a> \
													<p class="currentTextHolder">0/0</p> \
													<a href="javascript:void(0);" class="pp_arrow_next">Next</a> \
												</div> \
											</div> \
										</div> \
									</div> \
								</div> \
								</div> \
							</div> \
							<div class="pp_bottom"> \
								<div class="pp_left"></div> \
								<div class="pp_middle"></div> \
								<div class="pp_right"></div> \
							</div> \
						</div> \
						<div class="pp_overlay"></div> \
						<div class="ppt"></div>',
				image_markup: '<img id="fullResImage" src="" />',
				flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
				quicktime_markup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',
				iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',
				inline_markup: '<div class="pp_inline clearfix">{content}</div>'
			});
		}
	});


	/*asukoha_kaart(aadress);*/
	// @17.03.2011 - lisandus parameeter new_zoom_value
	// @18.03.2011 - lisandus parameeter showContent (TRUE väärtuse korral kuvab bubble-akna)
	function asukoha_kaart(x, y, m_data, icon_image, layer_id, new_zoom_value, showContent)
	{
		/*
			google.maps.event.addListener(map, "idle", function(){
						google.maps.event.trigger(map, 'resize');
						map.setZoom( map.getZoom() );
						});
		*/

		// markeri koostamise fn
		this.fn = function(x, y, m_data, icon_image, layer_id, new_zoom_value, showContent){
			var center = new google.maps.LatLng(x, y);
			var options = {
				zoom: (typeof new_zoom_value != 'undefined' ? parseInt(new_zoom_value) : 7),
				center : center,
				mapTypeControl: true,
				mapTypeControlOptions: {
					style: google.maps.MapTypeControlStyle.DROPDOWN_MENU, 
					position: google.maps.ControlPosition.TOP_RIGHT
				},
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};

			var map = new google.maps.Map(document.getElementById(layer_id), options);
			var markers = [];
			//var infoWindow = new google.maps.InfoWindow({});

			if( icon_image == 'none' || !icon_image ){}
			else
			{
				var image = new google.maps.MarkerImage(icon_image, 
				  // This marker is 20 pixels wide by 32 pixels tall. 
				  new google.maps.Size(32, 32), 
				  // The origin for this image is 0,0. 
				  new google.maps.Point(0,0), 
				  // The anchor for this image is the base of the flagpole at 0,32. 
				  new google.maps.Point(0, 32));
			}

			for(var i=0;i<m_data.length;i++)
			{
				if( showContent ) var infoWindow = new google.maps.InfoWindow({});

				var bodytxt = ( m_data[i].info == '' ? m_data[i].title : m_data[i].info.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/g, '"') );
				var latLng = new google.maps.LatLng(m_data[i].latitude, m_data[i].longitude);

				if( icon_image == 'none' || !icon_image )
				{
					var marker = new google.maps.Marker({
						position:latLng,
						title:m_data[i].title,
						draggable:false
					});
				}
				else
				{
					var marker = new google.maps.Marker({
						position:latLng,
						title:m_data[i].title,
						icon:image,
						draggable:false
					});
				}

				if( showContent ){
					infoWindowHtml = '<div class="gmap_sisu" style="height:' + (bodytxt.length+10) + 'px;">' + bodytxt + '<\/div>';
					infoWindow.setContent(infoWindowHtml);
					infoWindow.open(map, marker);
				}

				markers.push(marker);
			}

			google.maps.event.trigger(map, 'resize');

			var mc = new MarkerClusterer(map, markers);
		};


		/* kontakt */
		if( $('#kontaktinfo').length > 0 ) // $('.scroll-pane').length > 0
		{
			$.getScript(kodulehe_aadress + 'js/markerclusterer.js', function(){
				// kontaktiinfo
				$('.t2psem_info a').click(function(e){
					e.preventDefault();

					var rel = $(this).attr('rel'),
						google_map_layer = $('#google-map'),
						google_map_by_lang_name = $('#asukoha-kaardi-kiht').attr('class');

					$('.t2psem_info a').removeClass('valitud').hide();
					$(this).addClass('valitud');

					if( rel == 'tapsem-info-kaardil' ){
						$(google_map_layer).hide();
						$('a[rel="google-map-kaardil"]').show();
					} else {
						$(google_map_layer).show();
						$('a[rel="tapsem-info-kaardil"]').show();

						//if( $(this).is(':hidden') ) $(this).show();

						if( typeof showContent == 'undefined') showContent = true;

						if( google_map_by_lang_name == 'lang_est' ){
							//new_zoom_value = 17;
						} else {
							new_zoom_value = 4;
						}

						fn(x, y, m_data, icon_image, layer_id, new_zoom_value, showContent);
					}
				});

				$('a[rel="google-map-kaardil"]').addClass('valitud').trigger('click');
			});
		} // kontaktinfo
	}// func
}


/*
	Abiunktsioonid
	==============
*/
/*
	uus popup aken
	--------------
*/
function uus_popup_aken(link, laius, korgus)
{
	if(!laius) var laius = 800; // 770
	if(!korgus) var korgus = 600; // 650

	var left = parseInt((screen.availWidth/2) - (laius/2));
	var top = parseInt((screen.availHeight/2) - (korgus/2));

	window.open(link, '_blank', 
		'scrollbars=yes,toolbar=no,location=no,status=no,width=' + laius + ',height=' + korgus 
		+ ',screenX=' + left + ',screenY=' + top);
};


	function edasimyyjad_gmap_kaart(x, y, m_data, icon_image, layer_id, new_zoom_value){
		var zoom_lvl = (typeof new_zoom_value != 'undefined' ? parseInt(new_zoom_value) : 7);

		var myLatlng = new google.maps.LatLng(58.756805, 25.466309);
		var options = {
			zoom: zoom_lvl,
			minZoom: zoom_lvl,
			center: myLatlng,
			mapTypeControl: true,
			mapTypeControlOptions: {
				style: google.maps.MapTypeControlStyle.DROPDOWN_MENU, 
				position: google.maps.ControlPosition.TOP_RIGHT
			},
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};

		var map = new google.maps.Map(document.getElementById(layer_id), options);
		var markers = [];

		if( icon_image == 'none' || !icon_image ){
			var image = new google.maps.MarkerImage(icon_image, 
				new google.maps.Size(32, 32), 
				new google.maps.Point(0, 0), 
				new google.maps.Point(0, 32)
			);
		}

		for(var i=0;i<m_data.length;i++){
			var sites = m_data[i];
			var siteLatLng = new google.maps.LatLng(sites.latitude, sites.longitude);

			var marker_opts = {
				position: siteLatLng,
				map: map,
				title: sites.title,
				html: (sites.info == '' ? sites.title : sites.info.replace(/&amp/g, '&').replace(/&lt;/g, '<').replace(/&quot;/g, '"') )
			}

			if( icon_image == 'none' || !icon_image ){
			} else {
				marker_opts.icon = image;
			}

			var marker = new google.maps.Marker(marker_opts);

			google.maps.event.addListener(marker, 'click', function(){
				infoWindow.setContent(this.html);
				infoWindow.open(map, this);
			});
		}

		infoWindow = new google.maps.InfoWindow({
			content: ''
		});
	}



