var HY =  {};

// setup Shadowbox configuration
Shadowbox.loadSkin('classic', '/js/shadowbox/skin/');

function city_blur() 
{ 
    if ($(this).val() == "") 
    { 
        $(this).hide(); 
        $('#originating_city').show(); 
    } 
}

function originating_country_blur()
{
	var other = $('#originating_country_other').val();
	
	if (other == "")
	{
		$('#originating_country_other_fill').hide();
		$('#originating_country').show();
		$('#originating_country').val(0);
		
		$('#originating_city_other_fill').hide();
		$('#originating_city').show();
		$('#originating_city').html('<option value="">Select a City</option>');
	}
}

function originating_city_blur()
{
	var other = $('#originating_city_other').val();
	if (other == "" || other == "Other")
	{
		$('#originating_city_other').hide(); 
		$('#originating_city').show();
		$('#originating_city').val(0);
	}
}


function destination_country_blur()
{
	var other = $('#destination_country_other').val();
	
	if (other == "")
	{
		$('#destination_country_other_fill').hide();
		$('#destination_country').show();
		$('#destination_country').val(0);
		
		$('#destination_city_other_fill').hide();
		$('#destination_city').show();
		$('#destination_city').html('<option value="">Select a City</option>');
	}
}

function destination_city_blur()
{
	var other = $('#destination_city_other').val();
	if (other == "" || other == "Other")
	{
		$('#destination_city_other').hide(); 
		$('#destination_city').show();
		$('#destination_city').val(0);
	}
}

//this is it
$("#originating_country").change(function()
{ 
	$("#originating_city").html(''); // clear dropdown 
 
	if (this.value != "Other")
	{
		$("#originating_country_other").remove();
		$("#originating_city_other").remove();
		
		$('#originating_city').append("<option value=''>Select City</option>");

		$.getJSON("/en/stories/cities/?country=" + this.value, function(json){
			$.each(json.cities, function (i, city){
				if ($("#originating_country :selected").val() == 'South Africa' || $("#originating_country :selected").val() == 'New Zealand' || $("#originating_country :selected").val() == 'Australia') {
					if ($.find("#originating_city_other") == false) {
						$("#originating_city").parent().append(" <input type=\"text\" id=\"originating_city_other\" name=\"originating_city_other\" value='" +  window.default_originating_city_other + "' onblur=\"javascript:originating_city_blur()\" />");
					}
				}

				$("#originating_city").append("<option value=\"" + city.name + "\">" + city.name + "</option>");
			});
		});
	}
	else
	{	
		$('#originating_country_other_fill').html(" <input type=\"text\" id=\"originating_country_other\" name=\"originating_country_other\" value='" +  window.default_originating_country_other  + "'  onblur=\"javascript:originating_country_blur()\" />");			
		$('#originating_country_other_fill').css({'display' : 'block'});
		$('#originating_country_other').focus();
		
		$('#originating_country').hide();
						
		$("#originating_city_other_fill").html(" <input type=\"text\" id=\"originating_city_other\" name=\"originating_city_other\" value='" +  window.default_originating_city_other  + "' onblur=\"javascript:originating_city_blur()\" />");
		$('#originating_city_other_fill').css({'display' : 'block'});
		$('#originating_city').html('<option value="other" selected="selected">Other</option>');
		
		$('#originating_city').hide();
	}
});

// CHANGE "other" to city
$("#originating_city").change(
function()
{
	if (this.value != "Other")
	{
		$("#originating_city_other").hide();
	}
	else
	{
		// if ($.find("#originating_city_other") == false) {
			$("#originating_city_other_fill").html(" <input type=\"text\" id=\"originating_city_other\" name=\"originating_city_other\" value='" + window.default_originating_city_other + "' onblur=\"javascript:originating_city_blur();\" />");
			$('#originating_city').hide();
			$('#originating_city_other_fill').show();
			$('#originating_city_other').focus();
		// }
	}
});


$("#destination_country").change(
    function()
    {
		$("#destination_city").html(''); // clear dropdown 

		if (this.value != "Other")
		{
			$("#destination_country_other").remove();
			$("#destination_city_other").remove();
			
			$('#destination_city').append("<option value=''>Select City</option>");

			$.getJSON("/en/stories/cities/?country=" + this.value, function(json){
				$.each(json.cities, function (i, city){
					if ($("#destination_country :selected").val() == 'South Africa' || $("#destination_country :selected").val() == 'New Zealand' || $("#destination_country :selected").val() == 'Australia') {
						if ($.find("#destination_city_other") == false) {
							$("#destination_city").parent().append(" <input type=\"text\" id=\"destination_city_other\" name=\"destination_city_other\" value='" +  window.default_destination_city_other  + "' onblur=\"javascript:destination_city_blur()\" />");
						}
					}

					$("#destination_city").append("<option value=\"" + city.name + "\">" + city.name + "</option>");
				});
			});
		}
		else
		{	
			$('#destination_country_other_fill').html(" <input type=\"text\" id=\"destination_country_other\" name=\"destination_country_other\" value='" +  window.default_destination_country_other  + "' onblur=\"javascript:destination_country_blur()\" />");			
			$('#destination_country_other_fill').css({'display' : 'block'});
			$('#destination_country_other').focus();

			$('#destination_country').hide();

			$("#destination_city_other_fill").html(" <input type=\"text\" id=\"destination_city_other\" name=\"destination_city_other\" value='" +  window.default_destination_city_other  + "' onblur=\"javascript:destination_city_blur()\" />");
			$('#destination_city_other_fill').css({'display' : 'block'});
			$('#destination_city').html('<option value="other" selected="selected">Other</option>');

			$('#destination_city').hide();
		}
	
	
        // $("#destination_city").html('');
        //         
        //         if (this.value != "Other")
        //         {
        //             $("#destination_country_other").remove();
        //             $("#destination_city_other").remove();
        // 
        //             $.getJSON("/en/stories/cities/?country=" + this.value, function(json){
        //                 $.each(json.cities, function (i, city){
        //                     if ($("#destination_country :selected").val() == 'South Africa' || $("#destination_country :selected").val() == 'New Zealand' || $("#destination_country :selected").val() == 'Australia') {
        //                         if ($.find("#destination_city_other") == false) {
        //                             $("#destination_city").parent().append(
        //                                 " <input type=\"text\" id=\"destination_city_other\" name=\"destination_city_other\" />"
        //                             );
        //                         }
        //                     }
        //                     
        //                     $("#destination_city").append(
        //                         "<option value=\"" + city.name + "\">" + city.name + "</option>"
        //                     );
        //                 });
        //             });
        //         }
        //         else
        //         {
        //             if ($.find("#destination_city_other") == false) {
        //                 $("#destination_country").parent().append(
        //                     " <input type=\"text\" id=\"destination_country_other\" name=\"destination_country_other\" />"
        //                 );
        //             }
        //             
        //             if (lang.indexOf('/submit-russian') > 0) {
        //                 var langOption = "<option value=\"Other\">Другие опции</option>";
        //             } else {
        //                 var langOption = "<option value=\"Other\">Other</option>";
        //             }
        //             
        //             $("#destination_city").append(langOption);
        //             
        //             if ($.find("#destination_city_other") == false)
        //             {
        //                 $("#destination_city").parent().append(
        //                     " <input type=\"text\" id=\"destination_city_other\" name=\"destination_city_other\" />"
        //                 );
        //             }
        //         }
        // 
        // 		$('#destination_city').val("Other");
        //     
});


    
$("#destination_city").change(function()
{
	
	if (this.value != "Other")
	{
		$("#destination_city_other").hide();
	}
	else
	{
		// if ($.find("#originating_city_other") == false) {
			$("#destination_city_other_fill").html(" <input type=\"text\" id=\"destination_city_other\" name=\"destination_city_other\" onblur=\"javascript:destination_city_blur();\" />");
			$('#destination_city').hide();
			$('#destination_city_other_fill').show();
			$('#destination_city_other').focus();
		// }
	}
	
});
// 

$(document).ready( function() // when the document is ready
{
	$('#originating_country').change();
	$('#destination_country').change();
    // Store so we can change english text to russian
    var lang = window.location.href;

    // loadCities();

	// Select All Newsletters - User Profile Email Alerts
	$("[name=updates_all]").click(
		function()
		{
			if ($("[name=updates_all]").is(":checked"))
			{
				$("#fieldset-user_email_group").find('.checkbox').each( function()
				{
					$(this).attr('checked', 'checked');
				});
			}	
			else
			{
				$("#fieldset-user_email_group").find('.checkbox').each( function()
				{
					$(this).attr('checked', '');
				});
			}
			$(this).blur();
		}
	);
	
    // Design for the elements on the comment form
    $('#comment-add').fadeIn('slow');

    //	make a formEraserHelper for each defined element
    $('#input_search').each( function()
    {
    	var fieldName	=	$(this).attr('name');
    	HY[fieldName]	=	new HY.formEraserHelper($(this));
    });
    
    //  if there is a flashmap div embed the map
    if($('#flashmap').length > 0)
    {    
		var params = {
		    wmode : 'opaque'
		};
		var flashvars = {
		    "urlString": "/en/default/global-map.xml"
		};
		var attributes = {
		    play : "true",
		    loop : "true",
		    menu : "true",
		    scriptaccess: "allow",
		    id : "map"
		};
		
		swfobject.embedSWF("/uploaded/HIAS_map.swf", "flashmap", "680", "400", "9.0.0", false, flashvars, params, attributes);  
	}

//    $.preloadImages("/img/layout/ajax-loader.gif"); // preload loader image
    
    //  initiate shadowbox
    Shadowbox.init();
    
    // ADD FCK Editor to the necessary areas
    $('.page_copy').each(function (index, object)
    {
        var oFCKeditor                                  = new FCKeditor( object.id );
        oFCKeditor.BasePath                             = "/js/fckeditor/";
        oFCKeditor.TemplatesXmlPath                      = '/js/fckeditor/fcktemplates.xml' ;
        oFCKeditor.Height                               = 475;
        oFCKeditor.Width                                = 500;
        oFCKeditor.ToolbarSet                           = 'Hydra';
        CKFinder.setupFCKeditor( oFCKeditor, '/js/ckfinder/');
        oFCKeditor.ReplaceTextarea() ;  
    });


    // disable submit buttons after click...
    $('form').submit(
        function()
        {
            inputTarget = $(this).find('.controls input:submit'); // SET submit target
            $( '<img src="/img/layout/ajax-loader.gif" alt="loading..." class="submit_loader" />' ).insertAfter(inputTarget); // APPEND loader animation
            inputTarget.attr('disabled', 'disabled'); // DISABLE target
        }
    );

    // HIAS help details toggle
    toggleDetails = function()
    {
        var details = $("#help_details").parent().parent();
        
        if (details.css("display") == 'none')
        {
            details.show();
        }
        else
        {
            details.hide();
        }
    }
    
    $("#help_details").parent().parent().hide();
    
    if ($("#was_helped_in").val() != 0)
    {
        $("#was_helped").attr("checked", "checked");
        toggleDetails();
    }
    
    $("#was_helped").change(function()
    {
        toggleDetails();
    });

    $("#krum_advanced_toggle").click(function() {
        $("#fieldset-advanced_group").toggle();
    });
    
    
    ///////////////////////////
    // Cloner
    var file_count = 1;
    
    $('.close').show();
    $('.add').show();
    
    function cloneElement(cloneTarget, counter)
    {
        var newElement = $(cloneTarget)
        .clone(true)
        .insertBefore(cloneTarget)
        .removeClass('cloner');
        
        updateElements(newElement, counter);
        
        newElement.siblings('.add').show();
        newElement.siblings('.controls').show();
        
        file_count += 1;
    }
    
    $('.close a').click(function()
    {
        $(this).parent().parent().fadeOut(300, function()
        {
            $(this).remove();
            
        });
        return false;
    });
    
    function updateElements(updateTarget, counter)
    {
        $(updateTarget).attr('id', ($(updateTarget).attr('id') + counter));
        
        new_element_id = $(updateTarget).attr('id');
        
        $('#' + new_element_id + ' input').each(function()
        {
            updateAttr($(this), 'id', counter);
        });
        
        $('#' + new_element_id + ' label').each(function()
        {
            updateAttr($(this), 'for', counter);
        });
        
        $('#' + new_element_id + ' input').each(function()
        {
            //updateAttr($(this), 'name', '[]');
        });
    }
    
    function updateAttr(updateTarget, attrType, newVal)
    {
        return updateTarget.attr(attrType, (updateTarget.attr(attrType) + newVal));
    }
    
    $('.add a').click(function()
    {
        cloneElement('.cloner', file_count);
        return false;
    });

    $("#subject_not_me").click(function() {
        if ($(this).attr("checked")) {
			$('#mystory_about').show();
        } else {
			$('#mystory_about').hide();
        }
    });

	if ($('#subject_not_me').attr('checked')) {
		$('#mystory_about').show();
    }

});


jQuery.preloadImages = function() // preload function
{
  for (var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}


HY.formEraserHelper	=	function(fieldObj)
{
	var obj				=	this;					// 	cached "this"
	this.fieldObj		=	fieldObj;				//	the form field jQuery object
	this.initialValue	=	this.fieldObj.val();	//	initial value of the form field
	
	//	when focused on, if the value hasn't been changed, empty it
	this.fieldObj.focus(function()
	{
		if ( $(this).val() == obj.initialValue )
		{
			$(this).val('');
		}
	});
	
	//	when blurred, if the field is empty, populate it 
	this.fieldObj.blur(function()
	{
		if ( $(this).val() === '' )
		{
			$(this).val(obj.initialValue);
		}
	});
};	//	end formEraserHelper

