if (document.images) {
    var preload_image = new Array();
    var imageArray = new Array();    
        imageArray[0] = "http://media.intherooms.com/images/resources/animated-tree-small-white.gif";
        imageArray[1] = "http://media.intherooms.com/images/general/ajax-loader.gif";

    
    for (var i = 0; i < imageArray.length; i++) {
        preload_image[i] = new Image(); 
        preload_image[i].src = imageArray[i];    
    }
}

$(document).ready(function() {
		
		
	/* Tabs */ 
/*		
	$('#submit-tabs li a').click(function(){
		$('#submit-tabs li').removeClass('selected');
		$(this).parent().addClass('selected');
		$('#submit-listing .inner > div').hide();
		mystep = $(this).attr('rel');
		$('#submit-listing .inner div.'+ mystep).show();
	});
	
	$('.next1').click(function(){
		$('#submit-tabs li').removeClass('selected');
		$('#submit-tabs li.step2').addClass('selected');
		$('#submit-listing .inner div.step1').hide();
		$('#submit-listing .inner div.step2').show();
	});
	
	$('.next2').click(function(){
		$('#submit-tabs li').removeClass('selected');
		$('#submit-tabs li.step3').addClass('selected');
		$('#submit-listing .inner div.step2').hide();
		$('#submit-listing .inner div.step3').show();
	});
*/	
	/* First set of categories */
	
	$('#primary-category li label').click(function(){
		$(this).parent().parent().children('li').css({'color':'#444','font-weight':'normal'});
		$(this).parent().css({'color':'#59903A','font-weight':'bold'});

        $.ajax({
            type: "POST",
            url: "/listing/ajax/get_sub_categories",
            data: "category_id=" + $(this).children('input').val(),
            success: function(html, text) {
                $('#sub-cat-div').html(html);
			}
        });

		
		if ( $('#subcats').css('display') == 'none' )
			$('#subcats').fadeIn();
		if 	( $(this).children('input').val() == 1 ) {
			$('#treatment-form').show();
			$('#listing-description').show();
			$('#basic-info').hide();
		}
		else {
			$('#treatment-form').hide();
			$('#basic-info').show();
			$('#listing-description').hide();
		}
		
	});
	
	
	/* Second set of categories */
    
    // override event bubbing of clicked checkbox and trigger click event for label
    // which will handle checkbox status (checked/unchecked)
    $("#sub-category input:checkbox").click(function(e) {
        e.stopImmediatePropagation();
        $(this).parent().click();
    });

    $("#sub-category label").toggle(function(e) {
		$(this).css({'color':'#59903A','font-weight':'bold'});
		$(this).children().attr('checked','checked');
    },
    function(e) {
		$(this).css({'color':'#444','font-weight':'normal'});
		$(this).children().attr('checked','');
    });
    
    
    /* listing title counter */ 
    
    $('.listing-title').keyup(function() {
    	$('.counter-title').html( 60 - $(this).val().length + ' Left' );
    	if ( $(this).val().length == 60 )
    		$('.counter-title').css('color','red')
    	else
    		$('.counter-title').css('color','#999')
    });

	
	/* Counter fade in and out on blur */
    $('.listing-title').focus(function() {
    	$('.counter-title').fadeIn();
    });
    
    $('.listing-title').blur(function() {
    	$('.counter-title').fadeOut();
    });



    /* listing title counter */
    
    $('.listing-desc').keyup(function() {
    	$('.counter-desc').html( '<span style="color:green;font-weight:bold">FREE</span><br />' + (160 - $(this).val().length) + ' Left' );
    	if ( $(this).val().length == 160 )
    		$('.counter-desc').css('color','red')
    	else
    		$('.counter-desc').css('color','#999')
    	
    	if (($(this).val().length > 160) && ($(this).val().length < 320))
    		$('.counter-desc').html( '<span style="color:green;font-weight:bold">+ $1.50</span><br />160 to 320 Characters' );
    	else if (($(this).val().length > 320) && ($(this).val().length < 480))
    		$('.counter-desc').html( '<span style="color:green;font-weight:bold">+ $3.00</span><br />320 to 480 Characters' );
    	else if ($(this).val().length > 480)
    		$('.counter-desc').html( '<span style="color:green;font-weight:bold">+ $4.50</span><br />More than 480 Characters' );
    	
    });

	
	/* Counter fade out on blur */
	
	$('.listing-desc').focus(function() {
    	$('.upgrade-tinymce').fadeIn();
    	$('.counter-desc').fadeIn();
    });
	
    $('.listing-desc').blur(function() {
	    $('.counter-desc').fadeOut();
    	$('.upgrade-tinymce').fadeOut();
    });

	
	/* Turn on TinyMCE */
    
	$('.upgrade-tinymce a').click(function(){
        //$("#tinymce_flag").val(1);
    	$('.upgrade-tinymce').hide();
		$('textarea.listing-desc').tinymce({
			// Location of TinyMCE script
			script_url : '/js/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "safari,pagebreak,advhr,advlink,emotions,iespell,inlinepopups,preview,searchreplace,print,paste,noneditable,nonbreaking,template",
			width : 535,			
			height : 300,			
			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "bullist,numlist,hr,|,outdent,indent,blockquote,|,undo,redo,|,preview,|,forecolor,backcolor,",
			theme_advanced_buttons3 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : false,
			invalid_elements : "script,a"

			// Example content CSS (should be your site CSS)
			//content_css : "css/content.css",

			// Drop lists for link/image/media/template dialogs
			//template_external_list_url : "lists/template_list.js",
			//external_link_list_url : "lists/link_list.js",
			//external_image_list_url : "lists/image_list.js",
			//media_external_list_url : "lists/media_list.js"
		});
    	$('.counter-desc').html( '<span style="color:green;font-weight:bold">+ $4.99</span><br />Full Page' ).fadeIn();
    	$('.downgrade-tinymce').show();
	});
	
	
	$('.downgrade-tinymce a').click(function(){
        //$("#tinymce_flag").val(0);
		$('textarea.listing-desc').tinymce().remove();
		$('.downgrade-tinymce').hide();
		$('#temp').html($('textarea.listing-desc').val());
		$('textarea.listing-desc').val($('#temp').text());
    });
 
 
    
    // override event bubbing of clicked checkbox and trigger click event for label
    // which will handle checkbox status (checked/unchecked)
    $(".standard input:checkbox, .premium input:checkbox, .social input:checkbox").click(function(e) {
        e.stopImmediatePropagation();
        $(this).parent().find('label').click();
        $(this).parent().click();
    });
    
    $('.standard label, .premium label, .social label').toggle(function(){
    	$(this).parent().addClass('on');
    	$(this).parent().find('input:checkbox').attr('checked','checked');
    	$(this).siblings('input.lg').attr('disabled','');

    	var price = parseInt($("#upgrade_price").val()) + 1;
    	$("#upgrade_price").val(price);
    },
    function(){
    	$(this).parent().removeClass('on');
    	$(this).parent().find('input:checkbox').attr('checked','');
    	$(this).siblings('input.lg').attr('disabled','disabled');

    	var price = $("#upgrade_price").val() - 1;
    	$("#upgrade_price").val(price);
	});


    $('.package input:radio').click(function(e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        $(this).parent().find('label').click();
    });
    
    $('.package label').click(function(e){
        e.stopImmediatePropagation();
        e.stopPropagation();
        $("#package-div").find('.option').removeClass('on');
    	$(this).parent().addClass('on');
    	
    	var pkgRadio = $(this).parent().find('input:radio');
    	
    	pkgRadio.attr('checked','checked');
    	
    	if (pkgRadio.val() == 'free') {
    	   window.location.href='/listing/submit/checkout';
    	} else {
    	   $("#step-two-upgrades").fadeIn();
    	}
    	
    });

    $('.delete-me').live('click', function(e) {
        var ele = $(this);
        var mediaId = ele.attr('name');

        $.ajax({
            type: "POST",
            url: "/listing/ajax/delete_media",
            dataType: 'json',
            data: "media_id=" + mediaId,
            success: function(json, text) {
                ele.parent().fadeOut().remove();
			}
        });        
    });

    $('#step-one-form').bind('submit', function(e) {

        var errorMsg = 'Please fill in all required fields';
        var error = false;

        if ($('#treatment-form').css('display') == 'block') {
            $('#treatment-form input.req:text').each(function(){
                if (!$(this).val()) {
                    error = true;
                }
            });
        } else {
            $('#basic-info input:text').each(function(){
                if (!$(this).val()) {
                    error = true;
                }
            });
        }

        if (!$('textarea.listing-desc').val()) {
            error = true;
        }
        
        if (error) {
            alert(errorMsg);
            return false;
        }
        
        if ($('textarea:tinymce').html()) {
            $('#tinymce_description').val($('textarea.listing-desc').tinymce().getContent());
        }


        return true;
    });


    $('.remove-from-cart').bind('click', function(e) {
        var ele = $(this);
        var item = ele.attr('name');

        $.ajax({
            type: "POST",
            url: "/listing/ajax/remove_from_cart",
            dataType: 'json',
            data: "item=" + item,
            success: function(json, text) {
                if (json.success) {
                    ele.parent().parent().fadeOut().remove();
                    $('#box-table-a tr:even').addClass('zebra');
                    $('#box-table-a tr:odd').removeClass('zebra');
                    $('#total-price').html('$' + json.total_price);
                }
               
			}
        });        
    });


    $('.upgrade-listing-category label').bind('click', function(e) {
        var ele = $(this);
        var inputEle = ele.find('input');
        var checked = inputEle.attr('checked') ? 1 : 0;

        var string = inputEle.val();
        var array = string.split('|');
        
        var id = array[0];
        var price = array[1];

//alert('sub cat id: ' + array[0] + ' price: ' + array[1] + ' checked: ' + checked);
        
        $.ajax({
            type: "POST",
            url: "/listing/ajax/update_listing_category",
            dataType: 'json',
            data: "sub_category_id=" + id + "&upgrade=" + checked + "&price=" + price,
            success: function(json, text) {
                if (json.success) {
                    $('#total-price').html('$' + json.total_price);
                }
               
			}
        });        

    });


    $('.delete-listing').bind('click', function(e) {
        var ele = $(this);
        var listingId = ele.attr('name');
        
        if (confirm("Delete listing?\n\nIf the listing has a monthly charge, that charge will be canceled as well.")) {
            $.ajax({
                type: "POST",
                url: "/listing/ajax/delete_listing",
                dataType: 'json',
                data: "listing_id=" + listingId,
                success: function(json, text) {
                    if (json.success) {
                        ele.parent().parent().fadeOut().remove();
                        $('#box-table-a tr:odd').addClass('zebra');
                        $('#box-table-a tr:even').removeClass('zebra');
                        $('#total-price').html('$' + json.total_price);
                    }
                   
                }
            });
        }
    });
    
    $('#user-lead-form').submit(function(e) {
        tb_show("","#TB_inline?height=200&width=200&modal=true&inlineId=hidden-captcha");
        
        $('#captcha-word').focus();
        
        if ($('#hidden-word').val()) {
            return true;
        } 

        return false;
    });

    $('#captcha-button').bind('click', function(e) {
        var captchaWord = $('#captcha-word').val();
 
        if (captchaWord) {
            $('#hidden-word').val(captchaWord);
            $('#user-lead-form').submit();
        }
    });


    $("#lead-form").validate({
        submitHandler: function(form) {
        
            $.ajax({
                type: "POST",
                async: false,
                url: "/listing/ajax/captcha",
                data: 'cccid=' + $('#cccid').val() + '&word=' + form.word.value,
                dataType: "json",
                success: function(json, text) {
                    if (json.success) {
                        form.submit();
                    } else {
                        alert('Please re-enter phrase.');
                        $('#word').css('border', '1px solid red').focus();
                    }
                }
            });
        }
    });


});
