function colorToHex(color) {
    if (color.substr(0, 1) === '#') { return color; }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);
    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + "#" + rgb.toString(16);
};
function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}
function getContrast50(color){
    if (color == "transparent" || color == "rgba(0, 0, 0, 0)") return 'lighter';
    var hexcolor = colorToHex(color).replace("#","");
	return (h2d(hexcolor) > 0xffffff/2) ? 'lighter' : 'darker';
}

var color_selector = 'panel';

function clear_base() {
    $("#color-picker").hide();
    $("#instruction").hide();
    $('#seamless-action').hide();
}

jQuery.fn.getBg = function() {
    return $(this).filter(function() {
        // only checking for IE and Firefox/Chrome. add values as cross-browser compatibility is required
        var color = $(this).css('background-color');
        return color != 'transparent' && color != 'rgba(0, 0, 0, 0)';
    }).eq(0).css('background-color');
};

function update_design_style(target, type, contrast) {
    $.get(target, { type: type, contrast: contrast }, function(data) {
        $('#panel-profile img').attr('src', data.image); 
        $('#gallery-link').html(data.link);
        $('.title-header p').html(data.title);
        $('#panel-design').html(data.widths);
        
        if (data.higher) {
            $('#wall-accessories').hide();
            $('#wall-accessories-higher').show();
            $('#panel-texture').hide();
            $('#panel-texture-higher').show();
            $("#panel-profile").css({"top":"140px", "height":"135px"});
            $("#main-window #base-panel").css({"top":"133px", "height":"150px"});
            $("#main-window #panel-cap,#main-window #panel-cap-texture,#main-window #panel-cap-background").css({"top":"122px", "height":"11px"});
        } else {
            $('#wall-accessories-higher').hide();
            $('#wall-accessories').show();
            $('#panel-texture-higher').hide();
            $('#panel-texture').show();
            $("#panel-profile,#main-window #base-panel").css({"top":"165px", "height":"119px"});
            $("#main-window #panel-cap,#main-window #panel-cap-texture,#main-window #panel-cap-background").css({"top":"154px", "height":"11px"});
        }
        
    });
}


$(document).ready(function(){
    $(".email-placeholder").placeHolder({
        "text": "email",
        "active" : "#B3AFAF"
    });
    
    $(".password-placeholder").placeHolder({
        "text": "password",
        "active" : "#B3AFAF"
    });
    
    $('.show-more a').live('click', function(){
        $(this).parent('.show-more').hide();
        $(this).parent('.show-more')
            .next('.content-more').show()
            .next('.show-less').show();
        return false;
    });

    $('.show-less a').live('click', function(){
        $(this).parent('.show-less').hide();
        $(this).parent('.show-less')
            .prev('.content-more').hide()
            .prev('.show-more').show();
        return false;
    });

    $("#menu > li").hover(
        function(){
            $(this).children(".submenu-level-1").css({'visibility':'visible'})
        },
        function(){
            if ($(this).attr('class') != 'active-parent') 
                $(this).children(".submenu-level-1").css({'visibility':'hidden'})
        }
    );
    
    $("a.bookmark").click(function(e){
    	e.preventDefault(); // this will prevent the anchor tag from going the user off to the link
    	var bookmarkUrl = this.href;
    	var bookmarkTitle = this.title;

        if (isChrome) {
            alert('This function is not available in Google Chrome. Click the star symbol at the end of the address-bar or press Ctrl+D (Cmd+D on Mac) to create a bookmark.');
        } else if (window.sidebar) { // For Mozilla Firefox Bookmark
    		window.sidebar.addPanel(bookmarkTitle, bookmarkUrl,"");
    	} else if( window.external || document.all) { // For IE Favorite
    		window.external.AddFavorite( bookmarkUrl, bookmarkTitle);
    	} else if(window.opera) { // For Opera Browsers
    		$("a.bookmark").attr("href",bookmarkUrl);
    		$("a.bookmark").attr("title",bookmarkTitle);
    		$("a.bookmark").attr("rel","sidebar");
    	} else { // for other browsers which does not support
    		 alert('This function is not available in your browser.');
    	}
    	return false;
    });
    
    $('#share-links').toggle(
	    function(){
	        $('#sharebox').show();
	        return false;
	    },
	    function(){
	        $('#sharebox').hide();
	        return false;
	    }
	)

    $(".video-popup").live('click', function() {
        var el = $(this);
        url = el.attr("href");
        $.fancybox({
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'title': el.attr('title'),
            'overlayOpacity': 0.7,
            'href': url.replace(new RegExp("watch\\?v=", "i"), 'v/') + "?rel=0&hd=1&autoplay=1&fs=1",
            'width': 680,
            'height': 495,
            'type': 'swf',
            'swf': {
                'wmode': 'transparent',
                'allowfullscreen': 'true'
            }
        });
        return false;
    });
    if ($('#picker').length != 0) {
        $('#picker').farbtastic(function(color){
            
            if (color_selector == 'ac-panel') {
                $('#id_panel').val(color);
                $('#base-panel').css('background-color', color);
            } else if (color_selector == 'ac-cap') {
                $('#id_cap').val(color);
                $('#cap').css('background-color', color);
            } else if (color_selector == 'ac-wall') {
                $('#id_wall').val(color);
                $('#wall').css('background-color', color);
            }
        });

        $('#picker-close').live('click', function(){
           $("#color-picker").hide();
           return false;
        });
    }
    $('.advanced-color').live('click', function(){
        $("#instruction").hide();
        $('#seamless-action').hide();
        var last_active = $(this).parents('ul').find('.active');
	    last_active.removeClass('active');
	    $(this).addClass('active');
        color_selector = $(this).attr("id");
        $("#color-picker").show();
        return false; 
    });
    
    $('#seamless-action-link').live('click', function(){
        $("#color-picker").hide();
        $("#instruction").hide();
        if ($('#seamless-action').is(':visible')) {
            $('#seamless-action').hide();
        } else {
            $('#seamless-action').show();
        }
        return false; 
    });
	
	
	$('#panel-color .palette a').live('click', function(){
	    clear_base();
	    var last_active = $(this).parents('ul').find('.active');
	    last_active.removeClass('active');
	    $(this).addClass('active');
        var color = $(this).css('background-color');
        $('#base-panel').css('background-color', color);
        $('#id_panel').val($(this).html());
        var new_contrast = getContrast50(color);
        if (last_active.length) {
            var old_contrast = getContrast50(last_active.css('background-color'));
            if (old_contrast != new_contrast) {
                var target = $('#scrollbar .viewport a.active').attr('href');
                var type = $('#scrollbar input[name=type]:checked').val();
                update_design_style(target, type, new_contrast);
            }
        } else if (new_contrast == "darker") {
            var target = $('#scrollbar .viewport a.active').attr('href');
            var type = $('#scrollbar input[name=type]:checked').val();
            update_design_style(target, type, new_contrast);
        }
        return false; 
	});
	
	$('#panel-color .texture a:not(.empty)').live('click', function(){
	    clear_base();
	    var last_active = $(this).parents('ul').find('.active');
	    last_active.removeClass('active');
	    $(this).addClass('active');
	    var target = $(this).attr("href");
	    $.get(target, function(data) {
	        $('#panel-texture img').attr("src", data.texture);
        }, "json");
        return false;
	});
	
	$('#panel-color .texture a.empty').live('click', function(){
	    $(this).parents('ul').find('.active').removeClass('active');
	    $('#panel-texture img').attr("src", 'blank.gif');
	    return false;
	});
	
	$('#cap-color .palette a').live('click', function(){
	    clear_base();
	    var last_active = $(this).parents('ul').find('.active');
	    last_active.removeClass('active');
	    $(this).addClass('active');
        var color = $(this).css('background-color');
        $('#panel-cap-background').css('background-color', color);
        $('#panel-base-background').css('background-color', color);
        $('#id_cap').val($(this).html());
        return false; 
	});
	
	$('#cap-color .texture a:not(.empty)').live('click', function(){
	    clear_base();
	    var last_active = $(this).parents('ul').find('.active');
	    last_active.removeClass('active');
	    $(this).addClass('active');
	    var target = $(this).attr("href");
	    $.get(target, function(data) {
	        $('#panel-cap-texture img').attr("src", data.cap_texture);
	        $('#panel-base-texture img').attr("src", data.base_texture);
        }, "json");
        return false;
	});
	
	$('#cap-color .texture a.empty').live('click', function(){
	    $(this).parents('ul').find('.active').removeClass('active');
	    $('#panel-cap-texture img').attr("src", 'blank.gif');
	    $('#panel-base-texture img').attr("src", 'blank.gif');
	    return false;
	});
	
	$('#wall-color .palette a').live('click', function(){
	    clear_base();
	    var last_active = $(this).parents('ul').find('.active');
	    last_active.removeClass('active');
	    $(this).addClass('active');
        var color = $(this).css('background-color');
        $('#wall').css('background-color', color);
        $('#id_wall').val($(this).html());
        return false; 
	});

    // Changing the panel design in the designer's window
	$('#scrollbar .viewport a').live('click', function(){
	    clear_base();
	    var last_active = $(this).parent().find('.active');
	    last_active.removeClass('active');
	    $(this).addClass('active');
	    var target = $(this).attr("href");
	    
	    if (target == '#') {
	        $("#panel-profile").hide();
	        $('#gallery-link').html('&nbsp;');
	        $('.title-header p').html('no design');
	        return false;
	    };
	    var sid = $(this).attr("id");
	    var id = sid.substr(3);
	    $('#id_design_style').val(id);
	    $("#panel-profile").show();
	    var type = $('#scrollbar input[name=type]:checked').val();
	    var bg_color = $('#base-panel').css('background-color');
	    var contrast = getContrast50(bg_color);
	    update_design_style(target, type, contrast);
	    return false;
	});
	
	$('#panel-design .type').live('click', function(){
	    var type = $(this).attr('rel');
	    var bg_color = $('#base-panel').css('background-color');
	    var contrast = getContrast50(bg_color);
	    var target = $('#scrollbar .viewport a.active').attr('href');
	    update_design_style(target, type, contrast);
	    return false;
	});
	
	$('#dw-share-page-link').live('click', function(){
	    $('#dw-share-design').hide(); 
	    if ($('#dw-sharebox').css('display') != 'none') {
    	    $('#dw-sharebox').hide(); 
        } else {
            $('#dw-sharebox').show(); 
        }
        return false;
	});
	
	$('#dw-share-design-link').live('click', function(){
	    $('#dw-sharebox').hide(); 
	    if ($('#dw-share-design').is(':visible')) {
	        $('#dw-share-design').hide(); 
	    } else {
	        $('#dw-share-design').show(); 
        }
	    return false;
	});
	
	$('#dw-share-design .close').live('click', function(){
	    $('#dw-share-design').hide();
	    return false;
	});
	
	$("#mtf-form").live('submit', function(e) {
	    var form = $(this)
        $("#mtf-sending").show();
	    $.post(form.attr("action"), form.serialize(),
         function(data){
             if (data.success) {
                 form.parent().replaceWith(data.form);
             } else {
                 form.parent().replaceWith(data.form);
             }
         }, "json");
	    return false;
	});
	
	$("#form-share").live('submit', function(e) {
        e.preventDefault();
        var form = $(this)
        form.find("#cancel-share-dw-friend").hide();
        form.find("#sending-share-dw-friend").show();
        var form_data = form.serialize();
        if ($("#panel-cap-background").getBg())
            form_data += "&cap=" + RGBToHex($("#panel-cap-background").css("background-color"));        
        if ($("#wall").getBg())
            form_data += "&wall=" + RGBToHex($("#wall").css("background-color"));
        if ($("#base-panel").getBg())
            form_data += "&panel=" + RGBToHex($("#base-panel").css("background-color"));
        if ($("#id_design_style").val())    
            form_data += "&design_style=" + $("#id_design_style").val() ;
        if ($("#panel-design a.active span").html())
            form_data += "&panel_type=" + PanelTypeToInt($("#panel-design a.active span").html());
        if ($("#panel-color .texture a.active").html())
            form_data += "&panel_texture=" + $("#panel-color .texture a.active").html();
        if ($("#cap-color .texture a.active").html()) 
            form_data += "&cap_base_texture=" + $("#cap-color .texture a.active").html();
        
        $.post(form.attr("action"), form_data, function(data){
            if (data.success) {
                form.parent().replaceWith(data.form);
            } else {
                form.parent().replaceWith(data.form);
            }
            form.parent().show();
            form.find("#cancel-share-dw-friend").show();
            form.find("#sending-share-dw-friend").hide();
        }, "json");
        return false;
	});
	
	$("#form-contact").live('submit', function(e) {
	    var form = $(this)
	    form.parent().prepend('Sending...');
	    $.post(form.attr("action"), form.serialize(),
         function(data){
             form.parent().html($(data.content).find(".contactform"));
             form.parent().show();
             $('#id_info_from').trigger('change');
         }, "json");
	    return false;
	});
	
	$("#form-comment").live('submit', function(e) {
	    var form = $(this)
	    form.parent().prepend('Sending...');
	    $.post(form.attr("action"), form.serialize(),
         function(data){
             form.parent().html(data);
             form.parent().show();
         });
	    return false;
	});
	
	$('#id_info_from').live(isIE?'click':'change', function(){
	    if ($(this).val() == 6) {
	        $('#id_info_from_other').parents('tr').show();
	    } else {
	        $('#id_info_from_other').parents('tr').hide();
	    }
    });
    
    $('.gallery_page_menu a').live('click', function(){
        $('.gallery_page_menu a.active').removeClass('active');
        $(this).addClass('active');
    });

    function RGBToHex(color) {
        if (color.substr(0, 1) === '#') { return color; }
        var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
        var red = parseInt(digits[2]);
        var green = parseInt(digits[3]);
        var blue = parseInt(digits[4]);
        var rgb = blue | (green << 8) | (red << 16);
        return digits[1] + '#' + rgb.toString(16);
    };

    function PanelTypeToInt(width) {
        switch (width.toLowerCase()) {
            case "wide": return 3;
            case "narrow": return 2;
            default: return 1;
        }
    }
});

