/* Updates a custom form input based on inline date picker selections */
function dpUpdateInput(dateStr, inst) {
	// Input element is a custom setting passed to the datepicker when initiating it
	$(inst._settings.inputElement).val(dateStr);
}

/* Adds the news flash functionality */
function setupNewsFlash() {
	if($('#newsFlash').length>0){
		$('#newsFlashOpenButton').click(function(){
			$('#newsFlashExpand').toggle();
			$('#newsFlashOpenButton').toggle();
			$('#newsFlashCloseButton').toggle();
			return false;
		});
		$('#newsFlashCloseButton').click(function(){
			$('#newsFlashExpand').toggle();
			$('#newsFlashOpenButton').toggle();
			$('#newsFlashCloseButton').toggle();
			return false;
		});
	}
}

function setUpSearchBar(){

	/* Hides the suggestions box when clicked on. The code that updates the value of the input box is
	   in search_autofill.js, as the hover event handler can only be defined after the code has been 
	   fetched with the AJAX call. */
	$('#suggestions').click(function(){
		this.innerHTML='';
		this.style.display='none';
	});
	
	/* Fetched a new set of suggestions every time a key is pressed */
	$('#navigationBarSearch').keyup(function(){
		//$('#suggestions').hide(); // Hiding between updates, optional
		// Trim and check input length
		if (this.value.replace(/^\s+|\s+$/g, '').length > 1) {
			loadXMLDoc('/suggestions.php?fn=&fl=default&d=default&sc=e8e8e8&usc=ffffff&rfs=1&q='+this.value);
		}
	});
	
	/* hides the suggestions box when cursor is moved off it */
	$('#suggestions').hover(
		function(){
		
		},
		function(){
			$(this).css('display','none');
		}
	);
	
	/* Removes the autocomplete feature from the input */
	$('#navigationBarSearch').attr('autocomplete', 'off');
	
}

function setupFormChecks(){
	/* registration form checker */
	/* actual functions are in form_register_checks.js */
	if($('#register1').length>0){
		$('#register1').submit(function(){
			preValidateForm(this.id);
			return false;
		});
		
	/*	$('#formRegisterSubmit').click(function(){
			preValidateForm($("#register1").attr('id'));			
			return false;
		});*/
	}


	/* textarea length checks */
	//TODO: make the function more generic
	/* Nomination news form descripton length check */
	if($('#T0_DESCRIPTION').length>0){
		var formNominationDescriptionMaxLen = $('#T0_DESCRIPTION').parent().find('input').val();
	
		$('#T0_DESCRIPTION').keyup(function(){
			var html = $(this).val();
			var len = html.length;
			$(this).parent().find('input').val(formNominationDescriptionMaxLen-len);
			if(len > formNominationDescriptionMaxLen){
				$(this).val(html.substr(0,formNominationDescriptionMaxLen));
			}
		});
	}
	
	/* Calendar form descripton length check */
	if($('#formCalendarEventDescription').length>0){
		var formNominationDescriptionMaxLen = $('#formCalendarEventDescription').parent().find('input').val();
	
		$('#formCalendarEventDescription').keyup(function(){
			var html = $(this).val();
			var len = html.length;
			$(this).parent().find('input').val(formNominationDescriptionMaxLen-len);
			if(len > formNominationDescriptionMaxLen){
				$(this).val(html.substr(0,formNominationDescriptionMaxLen));
			}
		});
	}
}

isset = function (varname) {
    if (typeof(window[varname]) != 'undefined') {
        return true;
    } else {
        return (false);
    }
}

function setupFilterHelpLinks() {
	$('#filterHelpLink').click(function(){
		$('#filterHelp').toggle();
		return false;
	});
}

// TODO: Make this look up all the elements that look like tab sets and 
// run the setup on the look-up results. Adding these manually will get old.
function setUpTabs(){
	setUpTabSet('calendarList');
	setUpTabSet('companyWatch');
	setUpTabSet('markkinaSeuranta1Osakkeet');
	setUpTabSet('markkinaSeuranta1Indeksit');
	setUpTabSet('markkinaSeuranta1Warrantit');
	//TODO: add function calls for the rest of the securities
	setUpTabSet('newsPromo');
	setUpTabSet('pictureSetLists');
	setUpTabSet('storyBrowser');
	setUpTabSet('storyFilter');
	setUpTabSet('storyList');
	setUpTabSet('videoLists');
	setUpTabSet('videoPictureSetBrowser');
	setUpTabSet('pikavipit');
}

function setUpTabSet(id){
	if($('#'+id).length>0){
		$('#'+id+' .xvTabs a').click(function(){
		
			// remove 'current' from other tabControls
			$(this).siblings().removeClass('current');
			
			// set 'current' on this tabControl
			$(this).addClass('current');
			
			// get the number of this tab
			var tab = $(this).attr('class');
			var tab = tab.split(' ');
			for(var i=0;i<tab.length;i++){
				if(tab[i].length>3 && tab[i].substr(0,3) == 'tab'){
					tabNumber = tab[i].substr(3);
				}
			}
			
			// hide all tabs... THIS seems to bug with nested tabsets
			$('#'+id+' .tabContent').css('display','none');
			
			// ..and show the one we've selected
			$('#'+id+' .tabContent'+tabNumber).css('display','block');
			
			// don't follow the link meant for non-js
			return false;
		});
	}
}

/* Shows and hides the subscribe tools. Function required by IE6, other browsers can use hover styles. */
function setupSubscribeTools() {
	$('#subscribeTools').hover(
		function () {
			$('#subscribeTools .dropdown').show();
		},
		function () {}
	);
	$('#subscribeTools').hover(
		function () {}, 
		function () {
			$('#subscribeTools .dropdown').hide();
		}
	);
}

function setupLightBoxes() {
	$('#story .lightBox').lightBox();
}

/* 
 * Unfortunately this hack does not do anything on IE6 (goes to the 
 * containers original position).
 *
 * This function fixes the problem that the anchor position loses behind the 
 * floating top ad. IE7 goes to the position of the container, not the anchor 
 * itself. On the other hand, Safari goes to the original position of the 
 * anchor and does not care about javascript repositioning. The way to 
 * handle both of these cases is to reposition anhor element by javascript 
 * remove the id from the anchor and add it into a new element inside the 
 * original anhor. The offset is defined in the ads.css file.
 *
 * Notes: For performance and simplicity reasons, each anchor must be 
 * 'div.anchor' element.
 */
function setupAnchorHack() {
	$('div.anchor').each(
		function (index) {
			$(this).prepend('<div id="' + this.id + '"></div>');
			this.id = '';
		}
	);
}

/* Puts each flash element under floating elements on Firefox and IE7. 
 * Fixes the annoying hover borders that IE7 shows around the flash content. 
 * The problem is that some of the objects are not available at document ready 
 * on IE7. So this function must be called on body's onload event.
 */
function fixFlashObjects() {
	//alert($('object').length);
	$('object').each(function (i) {
		// Fixes the z-index problems on Firefox
		this.wmode = 'opaque';
		// Removes the annoying hover borders on IE7 (and applies the wmode)
		this.outerHTML = this.outerHTML;
	});
	// Fixes the z-index problems on Firefox
	$('embed').attr('wmode', 'opaque');
}


/* Debug functionality */
var startTimeO = new Date;
var startTime = startTimeO.getTime();
function debugClear(msg) {
	if (document.getElementById('debug') != undefined) {
		document.getElementById('debug').value = "";
	}
}
function debugTime(msg) {
	var nowTimeO = new Date;
	var nowTime = nowTimeO.getTime();
	if (document.getElementById('debug') != undefined) {
		document.getElementById('debug').value += msg + " " + (nowTime-startTime) + "\n";
	}
}

sendToFriend = function (storyId, type, el, headline, permalink) {
    var h = el.parent().parent().parent();
    if (h.hasClass('toolBoxContainer')) {
        var pos = 'vertical';
    } else {
        var pos = 'horizontal';
        h = el.parent().parent();
        if ($.browser.msie && parseInt($.browser.version) == 7) { // IE7 has problems with Flash ads showing through the form
            location.href = 'http://www.itviikko.fi/laheta/uutinen/' + storyId;
            return false;
        }
    }
    if ($('#sendToFriendC').length > 0) {
        h.after($('#sendToFriendC'));
        $('#sendToFriendC').slideDown('slow');
    } else {
        h.after('<div id="sendToFriendC"><div id="sendToFriend" class="bubble"><div id="l66stf" class="loading">&nbsp;</div>\n</div>\n</div>\n');
        //$.get("/form_sendToFriend.php", { story_id: storyId, headline: $("#story h1:first").text().replace(/ä/g, '&auml;').replace(/ö/g, '&ouml;').replace(/Ä/g, '&Auml;').replace(/Ö/g, '&Ouml;'), url: window.location, bubble: 1 },
        $.get("/form_sendToFriend.php", { story_id: storyId, type: type, headline: headline.replace(/ä/g, '&auml;').replace(/ö/g, '&ouml;').replace(/Ä/g, '&Auml;').replace(/Ö/g, '&Ouml;'), url: permalink, bubble: 1 },
            function(data) {
                $('#l66stf').remove();
                $('#sendToFriend').append(data).slideDown('slow');
                $('a#closeSendToFriend').click(function() {
                    $('#sendToFriendC').slideUp('slow');
                });
                $('#sendToFriendF').submit(function() {
                    //alert('{vastaanottajat: ' + $('#vastaanottajat').val() + ', viesti: ' + $('#viesti').val() + ', lahettaja: ' + $('#lahettaja').val() + ', story_id: ' + $('#story_id').val() + ', ajax: \'1\'}');
                    $('#lahetaKaverilleSubmit').after('<div id="l66stf" class="loading inline">&nbsp;</div>\n');
                    $.post('/sendToFriend.php', {vastaanottajat: $('#vastaanottajat').val(), viesti: $('#viesti').val(), lahettaja: $('#lahettaja').val(), story_id: storyId, type: $('#type').val(), ajax: '1'}, function(r) {
                        $('#l66stf').hide().remove();
                        if (r.success == true) {
                            $('#sendToFriendF').replaceWith('<div class=\"success\">Viesti lähetetty.</div>\n');
                            $('#sendToFriendC').hide(5000, function() { $(this).remove(); });
                        } else {
                            r = r.errors.split(',');
                            $.each(r, function(r, e) {
                                $('#' + e + 'C').css({'background-color': '#def5ff'});
                            });
                            if ($('#e66stf').length > 0) {
                                $('#e66stf').css({'background-color': 'yellow'}).animate({ backgroundColor: 'white' }, 'slow');
                            } else {
                                $('#lahetaKaverilleSubmit').before('<p id="e66stf" class="error"><strong>Hups!</strong> Jotain ei mennyt ihan oikein. Tarkista vaalean sinisellä korostetut kohdat.</p>\n');
                            }
                        }
                    }, 'json');
                    return false;
                });
        });
    }
    return false;
}