
var gpx = gpx || {};

$(document).ready(function() {   

	//png fix


	/*$('#mycarousel').jcarousel({
		  scroll: 1,
		  wrap: 'last'
	}); */

	
	function validateEmail(email) {
		return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
	}
	function validateMe(val_me) {
		return /^([a-zA-Z0-9_\-])+$/.test(val_me);
	}
	function validateUrl(val_url) {
		return /[A-Za-z0-9\.-]{1,}\.[A-Za-z]{2,}/.test(val_url);
	}
	function validateDescription(description) {
		if (description != 'add description' && description)
		{
			return true;
		}
		return false;
	}

	function hideHint(hint) {
		hint.hide();	
	}
	
	function showModal() {
			$('#icanhaz-modal').show();	
			$('#icanhaz-overlay').css({'background':'#000','opacity':'0.7'});
			$('#iCanHazFormShort').css({'opacity':'0.7'});
			//$('#icanhaz-features').css({'opacity':'0.7'});
			$('#icanhaz-search').css({'opacity':'0.5'});
			$('#icanhaz-featuredSlider').css({'opacity':'0.5'});
			$('#icanhaz-tagline').css({'opacity':'0.5'});
	}
    
    function hideModal() {
        $('#icanhaz-modal').hide();    
        $('#icanhaz-overlay').css({'opacity':'0'});
        $('#iCanHazFormShort').css({'opacity':'1'});
        //$('#icanhaz-features').css({'opacity':'1'});
        $('#icanhaz-search').css({'opacity':'1'});
        $('#icanhaz-featuredSlider').css({'opacity':'1'});
        $('#icanhaz-tagline').css({'opacity':'1'});
    }
    
	function showError(errors) {
		$('#icanhaz-hint').show();
		$('#icanhaz-hint').text(errors);
	}	

	$('#icanhaz-more, #icanhaz-submit, #iCanHazForm_submit, #icanhaz-modal span.input, #icanhaz-modal span.pro_input, #icanhaz-close, #icanhaz-yeap, #icanhaz-noneed').hover( 
		function() { 
			$(this).css('cursor','pointer');	
		},
		function() {
			$(this).css('cursor','normal');		
	});
	
	$('#icanhaz-more').click( function(e) { 
		var val_me = $('#iCanHazForm_short').val();
		var val_url = $('#iCanHazForm_long').val();
		var hint = $('#icanhaz-hint');
		//var errors = new Array();
		/*
		if (!validateMe(val_me)) {
			showError('Please enter a valid word.');
		}
		else if (!validateUrl(val_url))
		{
			showError('Please enter a valid URL.');		
		}
		else {   */
			showModal();
			hideHint(hint);
			if($.browser.msie && $.browser.version.substring(0,1) == '6') {
				var viewportHeight = $(window).height();
				$('#icanhaz-overlay').css({'height':viewportHeight, 'display':'block','overflow':'hidden','zoom':'1000','background':'#000'});
			}
/*		}		*/
	});
	
	$('#icanhaz-overlay:visible,#icanhaz-wrapper #icanhaz-features, #icanhaz-wrapper #icanhaz-tagline, #icanhaz-close').click( function() {
	    hideModal();
	});
	
	$('#icanhaz-submit').click( function() { 
		var val_me = $('#iCanHazForm_short').val();
		var val_url = $('#iCanHazForm_long').val();
		var hint = $('#icanhaz-hint');
		if (!validateMe(val_me)) {
			showError('Please enter a valid word.');
		}
		else if (!validateUrl(val_url))
		{
			showError('Please enter a valid URL.');		
		}
		else {
			hideHint(hint);
			$('#iCanHazForm').submit();	
		}											 	
	});

    function is_valid_form()
    {
        var email = $('#iCanHazForm_email').val();
        var description = $('#iCanHazForm_description').val();
        var is_valid = true;
            
        if ($('#iCanHazFormNotify span').hasClass('checked')) {
            if (validateEmail(email))
            {
                $('#iCanHazForm_email').next('.icanhaz-error').hide();
            } else {
                is_valid = false;
                $('#iCanHazForm_email').next('.icanhaz-error').show();
            }
        }
        if ( $('#iCanHazFormPromotion span').hasClass('checked')) { 
            if (validateDescription(description))
            {
                $('#iCanHazForm_description').next('.icanhaz-error').hide();
            } else { 
                is_valid = false;                
                $('#iCanHazForm_description').next('.icanhaz-error').show();

            }
        }
        
        if (is_valid)
        {
            return true;
        } else { 
            return false;
        }
    }
    
	$('#iCanHazForm').submit(function(){
	    return is_valid_form();
	});

	$('#iCanHazForm_submit').hover( 
        function() {
        $(this).addClass('modal_submit_hover'); },
        function() {
        $(this).removeClass('modal_submit_hover');
    });
    
    $('#iCanHazForm_submit').click(function() { 
        var valid = is_valid_form();
        
        if (valid)  {
            hideModal();
            
            $('#iCanHazForm_email').next('.icanhaz-error').hide();
            $('#iCanHazForm_description').next('.icanhaz-error').hide();
        }
        
        return true;
    });
    
	$('#icanhaz-more').hover( 
		function() {
		    $(this).addClass('more_options_hover'); },
		function() {
	        $(this).removeClass('more_options_hover');
	});
    
	$('#icanhaz-submit').hover( 
        function() {
        $(this).addClass('submit_hover');
        $('#icanhaz-accept').addClass('accept_hover'); },
        function() {
        $(this).removeClass('submit_hover');    
        $('#icanhaz-accept').removeClass('accept_hover');
    });
               
    $('input#icanhaz-yeap').hover(  
        function() {   
            $(this).removeClass('icanhaz-yeap');     
            $(this).addClass('icanhaz-yeap-hover');  
        },
        
        function() {
            $(this).removeClass('icanhaz-yeap-hover');  
            $(this).addClass('icanhaz-yeap');  
    });
    
     $('input#icanhaz-noneed').hover( 
            function() {
                $(this).removeClass('icanhaz-noneed');
                $(this).addClass('icanhaz-noneed-hover');     
            },
            
            function() {
                $(this).removeClass('icanhaz-noneed-hover');  
                $(this).addClass('icanhaz-noneed');     
        });
               

	/* modal */
	
	
	//ascund input-urile din form-ul din modal
	$('#icanhaz-modal div.element input.styled').each( function() {
		$(this).hide();
	});
	
	//clear value pentru input-uri text
	$('#iCanHazForm div.element input[type=text]:not(\'#iCanHazForm_long\')').each( function() {
		var initial_val = $(this).attr('title');       
		$(this).focus( function() {
			if ($(this).val() == initial_val ) {
				$(this).val('');
			}
		});            
		$(this).blur( function() {
			if ( !$(this).val() ) { 
				$(this).val(initial_val);			
			}
 		});
	});
    
    // IE fix 
    $('input#iCanHazForm_short').focus( function() {
        var initial_val = $(this).attr('title');     
        if ($(this).val() == initial_val ) {
            $(this).val('');
        } else {
            $('#icanhaz-hint').hide();
        }
    });
    
    /*$('input#iCanHazForm_short').blur( function() {
        
        var initial_val = $(this).attr('title'); 
        if ( !$(this).val() ) { 
            $(this).val(initial_val);            
        }
        
        // replacing blank spaces
        $(this).val($(this).val().replace(/ /g, '-'));
        
        var val_me = $(this).val();
                              
        if (val_me == '' || val_me == initial_val) return false;
        
        if (!validateMe(val_me)) {
            showError('Please enter a valid word.');
            return false;
        }  
          
        $.ajax({
                type: "GET",
                url: "/check_availability.php",
                data: "myWord="+val_me,                
                success: function(msg){
                    if (msg == 'false') {
                        showError('taken. pls choose another one.');
                    }
                }
            });
        
     });*/
     
     // checking availability on keyup, if the string is longer then 2 chars
	gpx.ih = {
		timer: null,
		data: {},
		clean: function(val) {
			return typeof val == 'string' ? val.replace(/ /g, '-') : val;
		},
		check: function(val) {
			//console.log('Check for '+val);
			$.ajax({
				type: "GET",
				url: "/check_availability.php",
				data: "myWord="+val,                
				success: function(msg){
					if (msg == 'false') {
						showError('taken. pls choose another one.');
					}
					else {
						$('#icanhaz-hint').hide();
					}
				}
			});
		}
	}
     $('#iCanHazForm_short').bind('keyup', function() { 
        if (this.value.length <= 2) {
            return false;
        }
		//console.log('ku '+gpx.ih.clean(this.value));
        gpx.ih.data.iCanHazForm_short = gpx.ih.clean(this.value);
		if(!gpx.ih.timer) {
			gpx.ih.timer = setInterval(function() {
				var val = gpx.ih.clean($('#iCanHazForm_short').val());
				if(gpx.ih.data.iCanHazForm_short == val) {
					clearInterval(gpx.ih.timer);
					gpx.ih.timer = null;
					gpx.ih.check(val);
				}
			}, 1000);
		}
     })
	.bind('blur', function(e) {
		var _c = gpx.ih.clean($('#iCanHazForm_short').val());
		$('#iCanHazForm_short').val(_c);
		clearInterval(gpx.ih.timer);
		gpx.ih.timer = null;
		gpx.ih.check(val);
	 });  
        
                                                                               
     
    // IE fix ended
     
	$('#icanhaz-modal div.element').each( function() {
		// ascund toate input-urile text
		$(this).find('input.input_text').hide();
		
		// toggle cu clasa checked
		$(this).find('span.input').click( function() { 
			$(this).toggleClass('checked');	
			$(this).parent().find('input.input_text').toggle();
			$(this).parent().find('label').toggle();
			var current_input = $(this);
			
			$('#icanhaz-wrapper #iCanHazForm #icanhaz-modal div.element input.input_text').each( function() {
						
				if ( $(this).parent().find('span.checked, span.pro_checked') != current_input )
				{
					//$(this).hide();	
				}	
			});
		
		});
		$(this).find('span.pro_input').click( function() { 
			$(this).toggleClass('pro_checked');	
			$(this).parent().find('input.input_text').toggle();
		

		});
		// atribui value pentru input-uri
		$(this).find('span').toggle( 
			function() { $(this).next().attr({'checked':'checked', 'value':'true'}); },
			function() { $(this).next().attr({'checked':'', 'value':'false'}); 
		});
		// check inputs la click pe label-uri
		$(this).find('label').click( function() {
			$(this).prev().prev().click();											  	
		});

	});

	
	//pentru track-uri este validata tot timpul optiunea
	$('#iCanHazFormTrack span').each( function() { 
		$(this).addClass('pro_checked');
	});

    
    $('#icanhaz-tagline').click(function () {
        window.location = '/';
    }); 

	if($.browser.msie && $.browser.version.substring(0,1) == '6') {
		/*$('#icanhaz-wrapper #icanhaz-tagline').pngfix();
		$('#iCanHazForm #iCanHazFormShort').pngfix();
		$('#iCanHazForm #iCanHazFormLong').pngfix();
		$('#icanhaz-more').pngfix();
		$('#icanhaz-accept').pngfix();
		$('#icanhaz-submit').pngfix();
		$('#icanhaz-modal').pngfix(); */		
		
		
	}
    
    $('#get_random').click(function () {
        $.ajax({
                type: "GET",
                url: "/get_random_link.php",
                data: "",                
                success: function(msg){
                    if (msg != '') {
                        $('#frama').attr("src", msg);
                    }
                }
            });
    }); 
    
    $('#get_next').click(function () {
        $.ajax({
                type: "GET",
                url: "/get_next.php",
                data: "id="+id+"&icanhaz="+icanhaz,
                success: function(json){
                    if (json == '') {
                        return ;
                    }
                    response = JSON.parse(json, function (key, value) {
                                    var type;
                                    if (value && typeof value === 'object') {
                                        type = value.type;
                                        if (typeof type === 'string' && typeof window[type] === 'function') {
                                            return new (window[type])(value);
                                        }
                                    }
                                    return value;
                                });
    
                    $('#frama').attr("src", response["url"]);
                    $('.querystring').html(response["icanhaz"]);

                    icanhaz = response["icanhaz"];
                    id = response["id"];
                                        
                    $('#direct_link').attr("href", response["url"]);
                    $('#direct_link').attr("title", response["url"]);
                }
            });
    });
    
    $('#get_previous').click(function () {
        $.ajax({
                type: "GET",
                url: "/get_previous.php",
                data: "id="+id+"&icanhaz="+icanhaz,
                success: function(json){
                    if (json == '') {
                        return ;
                    }
                    response = JSON.parse(json, function (key, value) {
                                    var type;
                                    if (value && typeof value === 'object') {
                                        type = value.type;
                                        if (typeof type === 'string' && typeof window[type] === 'function') {
                                            return new (window[type])(value);
                                        }
                                    }
                                    return value;
                                });
    
                    $('#frama').attr("src", response["url"]);
                    $('.querystring').html(response["icanhaz"]);

                    icanhaz = response["icanhaz"];
                    id = response["id"];

                    $('#direct_link').attr("href", response["url"]);
                    $('#direct_link').attr("title", response["url"]);
                }
            });
    });
                 
	
	$('.more').html('<p class="normal">it wuz delishious</p>');
    $('#icanhaz').hover( 
        function() {      
            $('.more').html('<a href="/">get your own lolcat</a>');
        },
        function() {
            $('.more').html('<p class="normal">it wuz dilishuz <br />kthxbai!</p>');
    }); 
  
    $('#direct_link').hover( 
        function() {   
            $(this).find('img').attr("src", static_route+'images/sign-redirect-hover.png');  
        },
        function() {
            $(this).find('img').attr("src", static_route+'images/sign-redirect.png');  
    });
    
    $('#random_link').hover( 
        function() {   
            $(this).find('img').attr("src", static_route+'images/sign-random-hover.png');  
        },
        function() {
            $(this).find('img').attr("src", static_route+'images/sign-random.png');  
    });
    //$('.more').html('<p class="normal">it wuz delishious</p>');
                       
});

