// JavaScript Document
function initBinding() { 


	// Add class last to the last module in a module panel
	$(document).ready(function(){
		$('.module-panel div:last-child').addClass('last');
    });
    
    //Add brochure hover color on brochure selection page
    $(document).ready(function() {
        $(".brochure .promo").unbind('mouseover').bind('mouseover', function() {
            $(this).addClass('promo-hover');
        });
        $(".brochure .promo").unbind('mouseout').bind('mouseout', function() {
            $(this).removeClass('promo-hover');
        });
    });

	// hide show function for descriptions
	$(document).ready(function(){
		$(function() {
			// Limit 
			var limit = 200;
			// place all p tags in an array
			var chars = $(".description p");
			// for each array item
			$.each(chars, function() {
				// place all text within variable				   
				var charLength = $(this).text();
				// if the text exceeds the limit then proceed
				if (charLength.length > limit) {
					// text under 207 place in this variable
					var visiblePart = $("<span> "+ charLength.substr(0, limit-1) +"</span>");
					// creat variable for dots
					var dots = $("<span class='dots'>... </span>");
					// text over 207 place in this variable
					var hiddenPart = $("<span class='more'>"+ charLength.substr(limit-1) +"</span>");
					// create more and less html
					var readMore = $("<span class='read-more'><img src='http://media.ef.com/_imgs/funnelpages2010//plus-button.gif' /></span>");
					var readLess = $("<span class='read-less'><img src='http://media.ef.com/_imgs/funnelpages2010//close-button.gif' /></span>");
					// create click function for read more button
					readMore.click(function() {
						// hide this read more button
						$(this).hide();
						// find dots and hide
						$(this).parent().children(".dots").hide();
						// slide toggle the hidden part
						$(this).parent().children(".more").slideToggle('slow')
						// show the read less button
						$(this).parent().children(".read-less").show();
		
					});
					// create click function for read less button
					readLess.click(function() {
						// hide this read less button
						$(this).hide();
						// find dots and show
						$(this).parent().children(".dots").show();
						// slide toggle the hidden part
						$(this).parent().children(".more").slideToggle('slow');
						// show the read more button
						$(this).parent().children(".read-more").show();
					});
					// recreate the paragraph within description with the above a values for visible text, dots, hidden text, and buttons
					$(this).empty()
						.append(visiblePart)
						.append(dots)
						.append(readMore)
						.append(hiddenPart)
						.append(readLess)
					$('span.more').hide();
				}
			});
		});
	});


	// function for the sliding of the program selections for program pages
	$(document).ready(function(){
		$('.program-selection-button').unbind('click').bind('click', function(){
			$('.program-selection').slideToggle(300);										  
		});
	});

	// start transforming form elements
	$(function() {
		//find all form with class jqtransform and apply the plugin
		$("form.jqtransform").jqTransform();
	});

	// start ui tabs for the contact section
	$(function() {
		// $('ul#main-contact-tabs').tabs();
		$('ul#sub-contact-tabs').tabs({ fx: { opacity: 'toggle' } });
		$('ul#agent-contact-tabs').tabs({ fx: { opacity: 'toggle' } });
	});

	/* fade and toggle effects for agents selection */
	$(document).ready(function(){
		$('#agent-contact-tabs').hide();
		$agentname = $('#agent-contact-tabs li:first-child').text();
		$('.agentSelectWrapper span').text($agentname);
		$('.agentSelectWrapper').click(function(){
			$('#agent-contact-tabs').slideToggle();
			return false;
		});
		$('.jqTransformSelectOpen').click(function(){
			$('#agent-contact-tabs').slideToggle();	
			return false;
		});	
		$('#agent-contact-tabs a').click(function(){
			$('#agent-contact-tabs').slideToggle();
			$agentname = $(this).text();
			$('.agentSelectWrapper span').text($agentname);
		});
	});


	$(document).ready(function(){
		$('.quick-search .forms-up .jqTransformSelectWrapper').css({zIndex: 1});
	});

	$(document).ready(function(){
		$('#heading .jqTransformSelectWrapper ul').addClass('buttons');
	});


	$(document).ready(function() {
	    /*
	    $("#left-col ul li a").unbind('mouseover').bind('mouseover', function() {
	        $(this).stop().animate({ color: '#00aeef' }, 200);
	    });
	    $("#left-col ul li a").unbind('mouseout').bind('mouseout', function() {
	        $(this).stop().animate({ color: '#9B9B9B' });
	    });
	    */
	    
	    
	    /*
	    //Keeps the selected color on the left menu
	    $("#left-col ul li a").click(function() {
	        $("#left-col ul li").each(function() {
	            $(this).removeClass('selected');
	        });
	        $(this).parent().addClass('selected');
	        return;
	    });
	    */

	    /*Go to URL link when you select a country from Top Panel Select dropdown */
	    $('a.others-select').click(function() {
	        window.location = $(this).attr("href");
	        return;
	    });

	});


	$(document).ready(function(){
		$('#footer ul li:first-child').addClass('first');
	});

		
		
	$(document).ready(function(){
		addContent = $('.home-address .info .content div').hide();
		$('.home-address .info .forms').show();
		$('.home-address .info .content div:first-child').show();
		$('.home-address .info .forms ul li a').click(function(){
			clickedAddId = $(this).attr('href');
			var index = clickedAddId.lastIndexOf("#");
			var filename = clickedAddId.substr(index);
			clickedAddId = filename.replace(/[#]/, "");
			addContentVis = $('.home-address .info .content div:visible');					
			$(addContent).each(function(){
				addId = $(this).attr('id');
				if(addId == clickedAddId){
					addContentFadeIn = $(this);
					$(addContentVis).fadeOut(function(){
						$(addContentFadeIn).fadeIn();
					});
				}
			});
			return false;
		});
	});



	$(function() {
	    // if the function argument is given to overlay,
	    // it is assumed to be the onBeforeLoad event listener
	    $("a[rel]").overlay({
	        expose: '#445566',
	        onBeforeLoad: function() {
	            // grab wrapper element inside content
	            var wrap = this.getContent().find(".contentWrap");
	            classContent = (this.getTrigger().attr("class"));
	            if (classContent == 'quick-search') {
	                urlPath = '/Forms/QuickSearchBox.aspx';
	                $('.simple_overlay').addClass('form-pop-up');
	                $('.simple_overlay').removeClass('text-pop-up');
	            } else {
	                urlPath = (this.getTrigger().attr("href"));
	                $('.simple_overlay').addClass('text-pop-up');
	                $('.simple_overlay').removeClass('form-pop-up');
	            }
	            // ajax call
	            $.ajax({

	                url: urlPath,
	                success: function(data) {
	                    // Queue functions
	                    $(wrap).queue(function() {
	                        // add new data - empty container and append data
	                        $(this).html(data);
	                        $(this).empty().append(data);
	                        // fade in conent and add a class
	                        //$(this).hide().fadeIn();
	                        // rebind jquery
	                        $('form').removeClass('jqtransformdone');
	                        initBinding();
	                        $(this).dequeue();
	                    });
	                }
	            });
	        }
	    });
	});





	$(document).ready(function(){
		$('#program-data').click(function(){
			// fade out all panels
			$('#right-col img').fadeOut(400);
			$('#right-col .content-panel').fadeOut(400, function(){
				// ajax call
				$.ajax({				
					url: 'program-data-level2.html',
					success: function(data) {
						// Queue functions
						$('#right-col').queue(function(){
							// add new data - empty container and append data
							$(this).html(data);
							$(this).empty().append(data);
							// fade in conent and add a class
							$(this).hide().fadeIn();
							// rebind jquery
							$('form').removeClass('jqtransformdone');
							initBinding();
							$(this).dequeue();
						});
					}
				});
				// loading image
				loading = '<div id="loading"><img src="http://media.ef.com/_imgs/funnelpages2010/ajax-loader.gif" /></div>';
				$('#right-col').empty().append(loading).hide().fadeIn('slow').ajaxStart(function() {
					$(loading).show();		
				}).ajaxStop(function(){
					$(loading).hide();
				});			
			});
			$(this).parent().addClass('selected');
			return false;
		});
	});

	$(document).ready(function() {
	    if ($('#heading h1').hasClass('china')) {
	        $('#heading h1').html('<img src="http://media.ef.com/_imgs/funnelpages2010/header/china_header.gif" alt="EF Education First" width="238px" height="30px" >');
	    }
	});

	$('#target-groups a').click(function() {
	    var hash = $(this).attr('name').replace('loadContent(', '').replace(')', '');
	    sethash(hash);
	    return false;
	});
	
	if (columnLoaded == false) {
	    controlLength = $('#control').length;
	    if (controlLength == 1) {
	        $('#content .program-selection ul.buttons li a').click(function() {
	            var hash = $(this).attr('name').replace('loadContent(', '').replace(')', '');
	            columnLoaded = false;
                /*
	            hashValue = window.location.hash;
	            hashValue = hashValue.replace('right-col', 'inner-content');
	            window.location.hash = hashValue;
                */
	            sethash(hash);
	            return false;
	        });
	    }
	    
	    $('#left-col a').click(function() {
	        var hash = $(this).attr('name').replace('loadContent(', '').replace(')', '');
	        sethash(hash);
	        return false;
	    });
	}

	function sethash(hash) {
	    hash = hash.replace(/^.*#/, '');
	    firstComma = hash.indexOf(',');
        secondCommaPos = firstComma + 1;
        hash2 = hash.substr(secondCommaPos);
        secondComma = hash2.indexOf(',');
        thirdCommaPos = secondComma + 1;
        hash3 = hash2.substr(thirdCommaPos);
        thirdComma = hash3.indexOf(',');
        fourthCommaPos = thirdComma + 1;
        hash4 = hash3.substr(fourthCommaPos);
        fourthComma = hash4.indexOf(',');
        var1 = 'agegroup=' + hash.substring(0, firstComma).replace(/'/gi, "").replace(' ', '');
        var2 = '/product='+hash2.substring(0, secondComma).replace(/'/gi, "").replace(' ', '');
        var3 = '/target=' + hash3.substring(0, thirdComma).replace(/'/gi, "").replace(' ', '');        
        var4 = '/site='+hash4.substring(0).replace(/'/gi, "").replace(' ', '');
        hash = var1 + var2 + var3 + var4;
        $.history.load(hash);
        return false;
    }



    
    
    
}

columnLoaded = false;
initBinding();



function pageload(hash) {
    if (hash) {
        firstEqual = hash.indexOf('/');
        secondEqualPos = firstEqual + 1;
        hash2 = hash.substr(secondEqualPos);
        secondEqual = hash2.indexOf('/');
        thirdEqualPos = secondEqual + 1;
        hash3 = hash2.substr(thirdEqualPos);
        thirdEqual = hash3.indexOf('/');
        fourthEqualPos = thirdEqual + 1;
        hash4 = hash3.substr(fourthEqualPos);
        fourthEqual = hash4.indexOf('/');
        ageGroupVar = hash.substring(0, firstEqual).replace('agegroup=', '');
        productVar = hash2.substring(0, secondEqual).replace('product=', '');
        targetVar = hash3.substring(0, thirdEqual).replace('target=', '');
        siteVar = hash4.substring(0).replace('site=', '');
        reloaded = 'true';
        if (targetVar == 'right-col') {
            if (siteVar == 'default') {
                if ($('#inner-content').hasClass('programs')) {
                    targetVar = 'right-col';
                    reloaded = 'false';
                    columnLoaded = true;
                } else {
                    targetVar = 'inner-content';
                    reloaded = 'true';
                    columnLoaded = false;
                }
            }
            if (siteVar == 'smallmarkets') {
                if ($('#inner-content').hasClass('small-market-clicked')) {
                    targetVar = 'right-col';
                    reloaded = 'false';
                    columnLoaded = true;
                } else {
                    targetVar = 'inner-content';
                    reloaded = 'true';
                    columnLoaded = false;
                }
            }
        }
        onClickVarData = hash.replace('agegroup=', "'").replace('/product=', "','").replace('/target=', "','").replace('/site=', "','");
        onclickVar = "loadContent(";
        onclickVar = onclickVar + onClickVarData;
        onclickVar = onclickVar + "')"
        loadContent(ageGroupVar, productVar, targetVar, siteVar, reloaded, onclickVar);

        
        if (pageNameVar == 'smallmarkets') {
            $('.module-panel').addClass('module-gradient');
        }
        
        
    } else {
        if (pageNameVar == 'default') {
            loadContent('', '', 'inner-content', 'default');
            $('.home-panel').fadeIn(400);
            $('.quick-search').fadeIn(400);
            $('.module-panel').fadeIn(400);
            $('.options').fadeIn(400);
            $('.options').addClass('no-heading');
            $('#footer').fadeIn(400);
            $('.home-address').fadeIn(400);
            $('#inner-content').removeClass('programs');
            columnLoaded = false;
        }
        else if (pageNameVar == 'smallmarkets') {
        loadContent('', '', 'inner-content', 'smallmarkets');
        $('.module-panel').addClass('module-gradient');
        
        }
    }
    return false;
}





// top bar function
$(document).ready(function() {
    var api1 = $(".top-panel-wrapper").expose({ api: true });
    opened = false;
    closedText = '';
    $('#close-top').hide();
    $('#close a').click(function() {
        $('.nav').hide();
        $('.top-panel').slideToggle(function() {
            if (opened == true) {
                api1.close()
                opened = false;
                $('.nav').show();
                $('#header').css({ zIndex: 9999 });
            } else {
                api1.load()
                opened = true;
                $('#close-top').fadeIn();
                $('#header').css({ zIndex: 10000 });
                $contentTop = $('.top-panel .content').html();
                if ($contentTop == '') {
                    // ajax call
                    $.ajax({
                        url: '/TopBar.aspx',
                        success: function(data) {
                            $('.top-panel .content').queue(function() {
                                $(this).html(data);
                                $(this).empty().append(data);
                                $('.top-panel .content div').hide().fadeIn();
                                $('form').removeClass('jqtransformdone');
                                initBinding();
                                $(this).dequeue();
                            });
                        }
                    });
                    loading = '<div id="loading"><img src="http://media.ef.com/_imgs/funnelpages2010/ajax-loader.gif" /></div>';
                    $('.top-panel .content').empty().append(loading).ajaxStart(function() {
                        $(loading).show();
                    }).ajaxStop(function() {
                        $(loading).hide();
                    });
                }
            }
        });
        if (closedText == 'true') {
            $(this).children().children().text(countryText);
            $(this).children().children().prepend("<img src=" + countryImg + " /> ");
            closedText = 'false';
            $(this).children().children().removeClass();
            $(this).children().children().addClass('arrow');
            $('#close-top').hide();
            $(this).css({ paddingLeft: 8 });
        } else {
            countryText = $(this).children().children().text();
            countryImg = $(this).children().children().children().attr('src');
            $(this).children().children().text('Close');
            $(this).children().children().removeClass();
            $(this).children().children().addClass('close');
            closedText = 'true';
            $(this).css({ paddingLeft: 10 });
        }
        return false;
    });

    $('#close-top a').click(function() {
        $('#close-top').fadeOut();
        $('.top-panel').slideToggle(function() {
            if (opened == true) {
                api1.close()
                opened = false;
                $('.nav').show();
                $('#header').css({ zIndex: 9999 });
            } else {
                api1.load()
                opened = true;
                $('#header').css({ zIndex: 10000 });
            }
        });
        if (closedText == 'true') {
            $('#close a').children().children().text(countryText);
            $('#close a').children().children().prepend("<img src=" + countryImg + " /> ");
            closedText = 'false';
            $('#close a').children().children().removeClass();
            $('#close a').children().children().addClass('arrow');
            $(this).css({ paddingLeft: 8 });
        }
        return false;
    });
});





$(document).ready(function() {
    $('#ajaxfade').click(function() {
        // fade out all panels
        $('.home-panel').fadeOut(400);
        $('.quick-search').fadeOut(400);
        $('.module-panel').fadeOut(400);
        $('.options').fadeOut(400);
        $('#footer').fadeOut(400, function() {
            // hide home address after fade out
            $('.home-address').hide();
            // ajax call
            $.ajax({
                url: 'program-data.html',
                success: function(data) {
                    // Queue functions
                    $('#inner-content').queue(function() {
                        // add new data - empty container and append data
                        $(this).html(data);
                        $(this).empty().append(data);
                        // fade in conent and add a class
                        $(this).hide().fadeIn().addClass('programs');
                        // remove home class
                        $('#content').removeClass('home');
                        // amend heading structure
                        $('#heading').append('<h1>&nbsp;</h1>');
                        // fade in options and remove class
                        $('.options').removeClass('no-heading').fadeIn();
                        // fade in footer
                        $('#footer').fadeIn();
                        // rebind jquery
                        $('form').removeClass('jqtransformdone');
                        initBinding();
                        $(this).dequeue();
                    });
                }
            });
            // loading image
            loading = '<div id="loading"><img src="http://media.ef.com/_imgs/funnelpages2010/ajax-loader.gif" /></div>';
            $('#inner-content').empty().append(loading).hide().fadeIn('slow').ajaxStart(function() {
                $(loading).hide();
            }).ajaxStop(function() {
                $(loading).hide();
            });
        });
        return false;
    });
});




// Form vallidation
$(document).ready(function(){
	
	$(".jqtransform").validate({				   
			// the errorPlacement has to take the table layout into account
			errorPlacement: function(error, element) {
				if ( element.is(":radio") )
					error.appendTo( element.parent().next().next() );
				else if ( element.is(":checkbox") )
					error.appendTo ( element.next() );
				else if ( element.is("select") )
					error.appendTo ( element.parent() );
				else if ( element.is("textarea") )
					error.appendTo ( element.parent().parent().parent().parent().parent().parent() );
				else
					error.appendTo( element.parent().parent().parent().parent() );
			}						   
		});
	
});



