CONTACT_US = "Please contact <a href='mailto:support@webmynd.com'>support@webmynd.com</a> if the problem persists";

var my_rating = 0;

var show_info = function(msg) {
    return show_message(msg, 'info')
}
var show_error = function(msg) {
    return show_message(msg, 'error')
}

var show_message = function(msg, cls) {
    $('#message_box').fadeOut("fast");
    $('#message_box').fadeIn("fast").animate({ opacity: 0.6 }, 3000).fadeOut("fast");
    $('#message_box').removeClass();
    $('#message_box').addClass(cls);
    $('#message_box').html(msg);
}

function switch_edit_tab(mode) {
	if (mode == 'css') {
		$('#editjsactive').hide();
		$('#editcssactive').show();
		$('#js').hide();
		$('#css').show();
	} else {
		$('#editcssactive').hide();
		$('#editjsactive').show();
		$('#css').hide();
		$('#js').show();
	}
}

function apply_design() {
                //First embed the css
		var styletext = $('#css')[0].value;
		var doc = document.getElementById("contentview").contentDocument;
                var body = doc.getElementsByTagName('body')[0];
		var header = doc.getElementsByTagName('head')[0];
		var curstyle = doc.getElementById('rgDesign');
		if (curstyle) {
			header.removeChild(curstyle);
		}
		var bodystyle = document.createElement('style');
		bodystyle.setAttribute('id', 'rgDesign');
		bodystyle.innerHTML = styletext;
		header.appendChild(bodystyle);
                if (!doc.getElementById('rgjQuery')) {
                    //Now embed jquery
                    var script = doc.createElement('script');
                    script.setAttribute('src','/static/javascript/jquery/jquery-1.3.2.min.js');
                    script.setAttribute('type','text/javascript');
                    script.setAttribute('charset','utf-8');
                    script.setAttribute('id', 'rgjQuery');
                    header.appendChild(script);
                    var script2 = doc.createElement('script');
                    script2.setAttribute('src','/static/javascript/jquery/jquery-ui-1.7.1.custom.min.js');
                    script2.setAttribute('type','text/javascript');
                    script2.setAttribute('charset','utf-8');
                    header.appendChild(script2);
                    var script3 = doc.createElement('script');
                    script3.setAttribute('src','/static/javascript/jquery/jquery.corners.min.js');
                    script3.setAttribute('type','text/javascript');
                    script3.setAttribute('charset','utf-8');
                    header.appendChild(script3);
                }
                //Now embed the javascript
                var styletext = $('#js')[0].value;
                var curstyle = doc.getElementById('rgJs');
                if (curstyle) {
                        header.removeChild(curstyle);
                }
                var bodyscript = document.createElement('script');
                bodyscript.setAttribute('id', 'rgJs');
                bodyscript.setAttribute('type', 'text/javascript');
                bodyscript.setAttribute('charset','utf-8');
                bodyscript.innerHTML = styletext + 'jQuery.ready();'; //Need to add the call to .ready() for the preview to work
                header.appendChild(bodyscript);
                init_cookie();
                show_info('Applied design to preview');
}

function feedback() {
	$('.lightbox').each(function (i) {
		$(this).hide();
	});
	$('#feedback_container').show();
	$('#feedback_text').attr('value','');
	toggle_lightbox();
	$('#feedback_text').focus();
}

function send_feedback() {
    $.getJSON("/feedback/", { message: "GALLERY: " + $('#feedback_text').val() });
	$('#feedback_welcome').hide();
	$('#feedback_thanks').show();
	toggle_lightbox()
}

function show_comments() {
	$('#disqus_container').fadeIn("fast");
	$('#show_comments_link').hide();
	$('#hide_comments_link').show();
}

function hide_comments() {
	$('#disqus_container').fadeOut("fast");
	$('#show_comments_link').show();
	$('#hide_comments_link').hide();
}

function check_email_address() {
	if ($('#ask_email').is(':visible') && $('#ask_email_input').val() == "") {
		alert('Please make sure you enter your email address.')
		$('#ask_email_input').focus();
	} else {
		if (String(document.location).match('edit_anon')) {
			$('#publish_link').attr('href', '/html/WebMyndRedesignGoogle.xpi');
		} else {
			$('#edit_form').submit();
		}
	}
}

function zero_rating() {
	for (i=1; i<=5; i++) {
		$('#myratingstar'+i).css({opacity:0.1});
	}
}

function hover_rating(rating) {
	zero_rating();
	for (i=1; i<=rating; i++) {
		$('#myratingstar'+i).css({opacity:0.9});
	}
}

function unhover_rating() {
	zero_rating();
	for (i=1; i<=my_rating; i++) {
		$('#myratingstar'+i).css({opacity:0.7});
	}
}

function set_rating(rating) {
	my_rating = rating;
	zero_rating();
	for (i=1; i<=rating; i++) {
		$('#myratingstar'+i).css({opacity:0.7});
	}
}

function set_avg_rating(rating) {
	var newwidth = (rating/5.0) * 165;
	$('#avgratingfg').css({width:newwidth+'px'});
}

function init_cookie(inserttitle) {
   //Prepare the css for cookie
   var stylenode = $('#css')[0];
   var styletext = "";
   if (stylenode && stylenode.value) {
       styletext = stylenode.value;
   } else if (stylenode) {
       styletext = stylenode.innerHTML;
   }
   styletext = encodeURIComponent(styletext);
   //Prepare the javascript for cookie
   var stylenode = $('#js')[0];
   var stylejs = "";
   if (stylenode && stylenode.value) {
       stylejs = stylenode.value;
   } else if (stylenode) {
       stylejs = stylenode.innerHTML;
   }
   stylejs = encodeURIComponent(stylejs);
   //Prepare the design title for cookie
   var stylenode = $('#name')[0];
   if (!stylenode) {
       stylenode = $('#designname')[0];
   }
   var styletitle = "";
   if (stylenode && stylenode.value) {
       styletitle = stylenode.value;
   } else if (stylenode) {
       styletitle = stylenode.innerHTML;
   }
   styletitle = encodeURIComponent(styletitle);
   //Prepare the design description for cookie
   var stylenode = $('#description')[0];
   var styledescription = "";
   if (stylenode && stylenode.value) {
       styledescription = stylenode.value;
   } else if (stylenode) {
       styledescription = stylenode.innerHTML;
   }
   styledescription = encodeURIComponent(styledescription);
   //If blank, insert some values for title and description and javascript
   if (inserttitle) {
       if (!styletitle || styletitle=='') {
           styletitle = "Design";
       }
       if (!styledescription || styledescription=='') {
           styledescription = "Design";
       }
       if (!stylejs) {
           stylejs = "";
       }
   }
   if (styletext) {
       var now = new Date();
       var expire = new Date( now.getTime() + 300000 ); //Cookie expires in 5 minutes
       document.cookie = 'styletext=; expires=' + expire + '; host=www.redesigngoogle.com; path=/tmp;';
       if (styletext.length > 4000) {
           var segs = Math.ceil(styletext.length / 4000);
           for (var i=0; i<segs; i++) {
               document.cookie = 'styletext' + i + '=' + styletext.substr(i*4000, 4000) + '; expires=' + expire + '; host=www.redesigngoogle.com; path=/tmp;'; 
           } 
           document.cookie = 'styletext=' + segs + '; expires=' + expire + '; host=www.redesigngoogle.com; path=/tmp';
       } else {
           document.cookie = 'styletext=' + styletext + '; expires=' + expire + '; host=www.redesigngoogle.com; path=/tmp;';
       }
       document.cookie = 'stylejs=' + stylejs + '; host=www.webmynd.com; expires=' + expire + '; path=/tmp;';
       document.cookie = 'styletitle=' + styletitle + '; host=www.webmynd.com; expires=' + expire + '; path=/tmp';
       document.cookie = 'styledescription=' + styledescription + '; host=www.webmynd.com; expires=' + expire + '; path=/tmp;';
   }
   if (String(document.location).match('edit_anon')) {
       document.cookie = 'stylenew=true; host=www.webmynd.com; expires=' + expire + '; path=/tmp'; 
   } else {
       document.cookie = 'stylenew=false; host=www.webmynd.com; expires=' + expire + '; path=/tmp';
   }
}

var register_install = function() {
    var chunks = $(this).id.split("_");
    if(chunks.length > 1) {
        var d_id = chunks[1];
        $.getJSON("/look/designs/install/" + d_id);
    } // else { fail silently like the cowards we are }
}

function delete_image(id) {
    $.getJSON("/look/image/delete?i_id=" + id,
        function(data){
            if (data.success) {
                show_info("Deleted image");
                $('#'+id).parent().fadeOut("fast"); 
            } else {
                show_error("Sorry! There was a problem removing this image. " + CONTACT_US);
            }
        }
    );
}

function cast_vote(design, rating) {
		set_rating(rating);
    $.getJSON("/look/designs/cast_vote/" + design + "/" + rating,
        function(data){
            if (data.success) {
            } else {
            }
        }
    );
}

function error(event, XMLHttpRequest, ajaxOptions, thrownError) {
    show_error("Sorry! There was a problem..." + CONTACT_US);
}

function image_save(response, statusText)  {
    if (statusText == "success" && response && response.success) {
        var imagenode = $("<li></li>");
        var input = $('<input class="focus_copy" type="text" readonly="true"></input>');
        input.attr("value", response.url);
        input.appendTo(imagenode);
        imagenode.appendTo($('#image_list'));
    } else {
        show_error("Sorry! There was a problem saving your image. " + CONTACT_US);
    }
}

function profile_save(response, statusText) {
    if (statusText == "success" && response && response.success) {
        show_info("Profile saved");
    } else {
        show_error("Sorry! There was a problem saving your profile. " + CONTACT_US);
    }
}

$(document).ready(function() {
    init_cookie();
    var options = { success: image_save, dataType: "json" };
		$('.install_link_css').click(register_install);
    $('#image_form').submit( function() { $(this).ajaxSubmit(options); return false; } );
    $('.cookie_click').click(init_cookie);
    $('input.focus_copy').focus(select_all);
    $('#submit_judge_score').click(submitTop5);
});

function select_all(ev) {
    this.select()
}

function checkTab(evt) {
    // Set desired tab- defaults to four space softtab
    var tab = "  ";
    var t = evt.target;
    var ss = t.selectionStart;
    var se = t.selectionEnd;
    // Tab key - insert tab expansion
    if (evt.keyCode == 9) {
        evt.preventDefault();
        // Special case of multi line selection
        if (ss != se && t.value.slice(ss,se).indexOf("\n") != -1) {
            // In case selection was not of entire lines (e.g. selection begins in the middle of a line)
            // we ought to tab at the beginning as well as at the start of every following line.
            var pre = t.value.slice(0,ss);
            var sel = t.value.slice(ss,se).replace(/\n/g,"\n"+tab);
            var post = t.value.slice(se,t.value.length);
            t.value = pre.concat(tab).concat(sel).concat(post);
            t.selectionStart = ss + tab.length;
            t.selectionEnd = se + tab.length;
        }
        // "Normal" case (no selection or selection on one line only)
        else {
            t.value = t.value.slice(0,ss).concat(tab).concat(t.value.slice(ss,t.value.length));
            if (ss == se) {
                t.selectionStart = t.selectionEnd = ss + tab.length;
            }
            else {
                t.selectionStart = ss + tab.length;
                t.selectionEnd = se + tab.length;
            }
        }
        }
    // Backspace key - delete preceding tab expansion, if exists
    else if (evt.keyCode==8 && t.value.slice(ss - 4,ss) == tab) {
        evt.preventDefault();
        t.value = t.value.slice(0,ss - 4).concat(t.value.slice(ss,t.value.length));
        t.selectionStart = t.selectionEnd = ss - tab.length;
    }
    // Delete key - delete following tab expansion, if exists
    else if (evt.keyCode==46 && t.value.slice(se,se + 4) == tab) {
        evt.preventDefault();
        t.value = t.value.slice(0,ss).concat(t.value.slice(ss + 4,t.value.length));
        t.selectionStart = t.selectionEnd = ss;
    }
    // Left/right arrow keys - move across the tab in one go
    else if (evt.keyCode == 37 && t.value.slice(ss - 4,ss) == tab) {
        evt.preventDefault();
        t.selectionStart = t.selectionEnd = ss - 4;
    }
    else if (evt.keyCode == 39 && t.value.slice(ss,ss + 4) == tab) {
        evt.preventDefault();
        t.selectionStart = t.selectionEnd = ss + 4;
    }
}

function showImages() {
    $('#useimages').show();
    $('#mainform').hide();
}

function hideImages() {
    $('#useimages').hide();
    $('#mainform').show();
}

function showProfile() {
    $('#profileform_table').show();
    $('#mainform').hide();
}

function hideProfile() {
    $('#profileform_table').hide();
    $('#mainform').show();
}

function saveProfile() {
    var options = { success: profile_save, dataType: "json" };
    $("#profileform").ajaxSubmit(options);
    hideProfile();
}

function thumbnail_options() {
	if ($("#custom_thumbnail:checked").length > 0) {
		$("#custom_thumbnail_url").show();
		$("#custom_thumbnail_option").css('color', '#f4f2f8');
		$("#auto_thumbnail_option").css('color', '#a59abb');
	} else {
		$("#custom_thumbnail_url").hide();
		$("#auto_thumbnail_option").css('color', '#f4f2f8');
		$("#custom_thumbnail_option").css('color', '#a59abb');
	}
}

function install_link2(id) {
        document.getElementById('css').innerHTML = document.getElementById(id+'css').innerHTML;
        document.getElementById('js').innerHTML = document.getElementById(id+'js').innerHTML; 
        document.getElementById('designname').innerHTML = document.getElementById(id+'designname').innerHTML;
        var evt = document.createEvent("Event");
        evt.initEvent("wmDesignInstall", true, false);
        this.dispatchEvent(evt);
        setTimeout(function() { window.open('http://www.google.com/search?q=jay+leno'); }, 1000);
}

function install_link() {
	var link = document.getElementById('all');
	var evt = document.createEvent("Event");
	evt.initEvent("wmDesignInstall", true, false);
	link.dispatchEvent(evt);
	if (navigator.userAgent.indexOf("Firefox")==-1) {
		$('.lightbox').each(function (i) {
			$(this).hide();
		});
		$('#ffonly_container').show();
		toggle_lightbox();
	}
}

function toggle_lightbox() {
	if ($('#light').is(':visible')) {
		$('#light').fadeOut("fast");
		$('#fade').fadeOut("fast");
	} else {
		$('#feedback_welcome').show();
		$('#feedback_thanks').hide();
		$('#light').fadeIn("fast");
		$('#fade').fadeIn("fast");
	}
}

function check_firstvisit() {
	var cookies = document.cookie.split(';');
        for (var i=0; i<cookies.length; i++) {
		if (cookies[i].match('firstvisit=false')) {
			return false;
		}
	}
	return true;
}


function top5HideRankings() {
	$("#top5").children().each(function(i) {
		$(".top5_rank", this).each(function() {
			$(this).hide();
		});
	});
}

function top5Rankings() {
	top5HideRankings();
	$("#top5").children().each(function(i) {
		var rank = i+1;
		$(".rank"+rank, this).show();
	});
}

function top5Sortable() {
	$("#top5").sortable({
		items: '.shortlist_design',
		cursor: 'move',
		opacity: 0.5,
		helper: 'clone',
		start: function(element) {
			top5HideRankings();
		},
		stop: function(element) {
			top5Rankings();
		}
	});
}

function addTop5(id) {
	if ($("#top5").children().size() < 5) {
		var design = $("#design"+id);
		design.fadeOut(500, function() {
			$("#top5").append(design.parent());
			$(".shortlist_add", design).hide();
			$(".shortlist_remove", design).show();
			top5Rankings();
			top5Sortable();
			design.fadeIn(500);
			$("#top5explain").fadeIn(500);
			if ($("#top5").children().size() == 5) {
				$("#submit_link").fadeIn(500);
			}
		});
	}
	
}

function removeTop5(id) {
	var design = $("#design"+id);
	design.fadeOut(500, function() {
		$("#shortlist").append(design.parent());
		$(".shortlist_add", design).show();
		$(".shortlist_remove", design).hide();
		top5Rankings();
		top5Sortable();
		$(".top5_rank", design.parent()).each(function() {
			$(this).hide();
		});
		if ($("#top5").children().size() == 0) {
			$("#top5explain").hide();
		}
		$("#submit_link").fadeOut(500);
		design.fadeIn(500);
	});
}

function submitTop5(ev) {
    var qs = '?';
    for(var idx=0; idx<5; idx++) {
        var des_cont = $('#top5').children()[idx];
        $(des_cont).children().each(function (i) {
            if (this.id.substring(0, 6) == 'design') {
                qs += this.id.substring(6) + '=' + (idx+1) + '&';
            }
        })
    }
    this.href = 'judge_vote' + qs;
}

function init() {
	if (navigator.userAgent.indexOf("Firefox")==-1) {
		$('.install_link_css').each(function (i) {
				$(this).attr('href','#');
		});
	} else { 
		$('#create_tab_right').attr('bgcolor','#393147');
		$('.create_link').each(function (i) {
				$(this).show();
		});
		$('#studio_link').show();
	}
	var first_visit = check_firstvisit(); //placeholder variable
	if (first_visit) {
		$('#welcome').fadeIn("fast");
                document.cookie = 'firstvisit=false; host=www.webmynd.com;';
	}
}

window.onload = init;
