$(document).ready(function () {
	
	$(".singleSelectClass").multiselect({
	   multiple: false,
	   header: false,
	   noneSelectedText: selectText,
	   height: 70,
	   minWidth:225,
	   selectedList: 1,
        click: function (event, ui) {
			singleSelectOnClick();
        },
		beforeopen: function(){		
			singleSelectBeforeOpen();
  	 }
	});	
							
	$(".getCodeButton").css({"opacity":0.5,"cursor":"default"});
	
	if(affiliateWidgetDetailID=='')
	{
		$(".widgetExpandSection").hide();
    	$(".widgetExpandSection:first").show();		
		$('#tabs .tabContents').hide();
		$('#tabs .tabContents:first').show();
		$('#tabs .tabsHeader li:first').addClass('active');
		var firstTab = $('.widgetDimensions:first a').attr('href');
		var widgetFormatFirst = $('.widgetDimensions:first a').attr('rel');
		$("#affiliateWidgetFormat").val(widgetFormatFirst);
		var widgetSizeFirst = $(firstTab + " .WidgetSize .active").attr('id');
		widgetSizeFirst = widgetSizeFirst.split("_");
		widgetSizeFirst = widgetSizeFirst[1];
		$("#affiliateWidgetSize").val(widgetSizeFirst);
	}
	else
	{
		$(".widgetExpand").addClass("expand");				

	}
	$(document).on("click",".widgetExpand", function () {
        $(this).toggleClass("expand");
        $(this).next(".widgetExpandSection").slideToggle();
    });
    $('#copyCode').click(function () {
        this.select();
    });
    

    $('#tabs .tabsHeader li a').click(function () {
        $('.widgetDimensions').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        var widgetFormat = $(this).attr('rel');
        $("#affiliateWidgetFormat").val(widgetFormat);
        $('#tabs .tabContents').hide();
        $(currentTab).show();
        var widgetSize = $(currentTab + " .WidgetSize .active").attr('id');		
        widgetSize = widgetSize.split("_");
        widgetSize = widgetSize[1];
        $("#affiliateWidgetSize").val(widgetSize);
        generateWidget();
        return false;
    });
	
	$(document).on("blur","#widgetName", function () {
		$("#widgetMode").val('preview'); 
		generateWidget();
    });

    $(document).on("click",".WidgetSizeInd", function () {
        $(this).parent(".WidgetSize").children(".WidgetSizeInd").removeClass("active");
        $(this).addClass("active");
        var widgetSize = $(this).attr('id');
        widgetSize = widgetSize.split("_");
        widgetSize = widgetSize[1];
        $("#affiliateWidgetSize").val(widgetSize);
        generateWidget();
    });
   
    $(document).on("click",".getCodeButton", function () {
        if ($(".widgetHolder").length > 0) {
            if(affiliateWidgetDetailID=='')
			{
				$("#widgetMode").val('save');
			}
			else if(affiliateWidgetDetailID!='')
			{
				$("#widgetMode").val('edit');	
			}
            var chkGenerate = generateWidget();
			if(chkGenerate)
			{
				$('html,body').animate({
					scrollTop: $("#getWidgetCode").offset().top
				}, 'slow');
				$(".getWidgetCode").fadeIn();
			}
        }
    });

});
$(function () {	
    $(".widgetCategory").multiselect({
        noneSelectedText: selectText,
        click: function (event, ui) {
            generateWidget();
        },
        checkAll: function () {			
            generateWidget();
        },
        uncheckAll: function () {
            generateWidget();
        }
    });

    $(document).on("change","#affiliateWidgetContentType,#affiliateWidgetContent,#languageID,#widgetFilter", function () {
		generateWidget()
    });
	
	if(affiliateWidgetDetailID!='')
	{	
		//Remove # From Color Selector
		$(".color").each(function () {
		 var thisColor = $(this).val();
		 thisColor = thisColor.replace('#','');
		 $(this).val(thisColor);
	   });	
	   generateWidget();
	}	
	
});

function generateWidget() {
	$(".getWidgetCode").hide();
    $(".getCodeButton").css({"opacity":0.5,"cursor":"default"});
	$(".widgetLoader").remove();
	$(".widgetErrorText").remove();	
	$(".widgetSuccessText").remove();	
	var widgetMode = $("#widgetMode").val();
    $(".getWidgetCode").hide();
    $("#previewDiv").html('');
    $("#previewDiv").html('<img src="' + GLOBAL_ROOT_PATH + '/public/default/affiliate/standard/images/ajax-widget-loader.gif" alt="" border="0" width="100" height="100" class="widgetLoader" />');

    var productCategories = '';
    var widgetFilter = '';
	var contentType = '';
	var widgetContent = '';
	var languageID = '';
    var checkWidgetName = true;
    //For productCategories
    $("input[name='multiselect_widgetCategory']:checked").each(function (index) {
        productCategories = productCategories + $(this).val() + ",";
    });
	//For Filters
    $("input[name='multiselect_widgetFilter']:checked").each(function (index) {
        widgetFilter = $(this).val();
    });
	//For contentType
    $("input[name='multiselect_affiliateWidgetContentType']:checked").each(function (index) {
        contentType = $(this).val();
    });
	//For content
    $("input[name='multiselect_affiliateWidgetContent']:checked").each(function (index) {
        widgetContent = $(this).val();
    });
	//For languageID
    $("input[name='multiselect_languageID']:checked").each(function (index) {
        languageID = $(this).val() ;
    });

    if (widgetMode == 'save' || widgetMode == 'edit') {
        if ($.trim($("#widgetName").val()) == '') {
            checkWidgetName = false;
        }
    }	
    if (productCategories != '' && widgetFilter!='' && checkWidgetName) 
	{
		$(".widgetLoader").after('<p class="widgetSuccessText">'+lblLoadingWidget+'</p>');	
        productCategories = productCategories.substring(0, productCategories.length - 1);
        $(".widgetCategory").val(productCategories.split(","));
		$("#affiliateWidgetContentType").val(contentType);
		$("#affiliateWidgetContent").val(widgetContent);
		$("#languageID").val(languageID);
        var formDetails = $('#widgetForm').serialize();
        $.ajax({
            type: 'POST',
            url: GLOBAL_BASE_PATH + "/widget/ajaxwidget/",
            data: formDetails,
            success: function (data) { 
                if (data.indexOf("sessionOut") > -1) {
                    window.location = GLOBAL_BASE_PATH + "/login/";
                    return false;
                }
                if (data.indexOf("Select All details") == -1) {
                    $("#previewDiv").html(data);
                    setAffWidget();					
                    if (widgetMode == 'save' || widgetMode == 'edit') {
                        var getCodeContent = '';
                        $("#widgetMode").val('preview');
                        var affiliateWidgetContent = $("#affiliateWidgetContent").val();
                        if (affiliateWidgetContent == 'Iframe') {
                            getCodeContent = '<iframe src="' + siteUrl + 'affiliate/widget/ajaxWidget/' + $("#affiliateWidgetID").val() + '/" frameborder="0" scrolling="no" width="' + $("#widgetWidth").val() + '" height="' + $("#widgetHeight").val() + '"></iframe>';
                        } else if (affiliateWidgetContent == 'JS') {
                            getCodeContent = '<script type="text/javascript">\nvar __widget = "' + $("#affiliateWidgetID").val() + '",__width="'+$("#widgetWidth").val()+'",__height="' + $("#widgetHeight").val() + '",__parent="",__od="";\n(function(){\n__od = document.createElement("script");\nvar __script = document.scripts[document.scripts.length - 1];\n __od.type = "text/javascript";\n __od.async = true;\n__od.src = ("https:" == document.location.protocol ? "' + httpsSiteUrl + '" : "' + siteUrl + '") + "public/widget/widget.js";\n__parent=__script.parentNode;\n__parent.insertBefore(__od, __script);\n})();\n</script>';
                        }
                        $("#copyCode").val(getCodeContent);						
                    }
					$(".getCodeButton").css({"opacity":1,"cursor":"pointer"});
                }
            }
        });


    }
	else
	{		
		if (productCategories == '')
		{
			$(".widgetLoader").after('<p class="widgetErrorText">'+errProductCategory+'</p>');			
		}
		
	}
	if ((widgetMode == 'save' || widgetMode == 'edit') && !checkWidgetName)
	{
		$("#previewDiv").html('');
        $("#previewDiv").html('<img src="' + GLOBAL_ROOT_PATH + '/public/default/affiliate/standard/images/ajax-widget-loader.gif" alt="" border="0" width="100" height="100" class="widgetLoader" />');
		$(".widgetLoader").after('<p class="widgetErrorText">'+errWidgetName+'</p>');	
		return false;
	}
	else
	{
		return true;
	}
}
function singleSelectOnClick()
{
	$("input[name='multiselect_affiliateWidgetContent']").parent(".ui-corner-all").removeClass("ui-state-active");	
	$("input[name='multiselect_affiliateWidgetContent']:checked").parent(".ui-corner-all").addClass("ui-state-active");
	$("input[name='multiselect_affiliateWidgetContentType']").parent(".ui-corner-all").removeClass("ui-state-active");	
	$("input[name='multiselect_affiliateWidgetContentType']:checked").parent(".ui-corner-all").addClass("ui-state-active");
	$("input[name='multiselect_languageID']").parent(".ui-corner-all").removeClass("ui-state-active");	
	$("input[name='multiselect_languageID']:checked").parent(".ui-corner-all").addClass("ui-state-active");
}
function singleSelectBeforeOpen()
{
	$("input[name='multiselect_affiliateWidgetContent']").parent(".ui-corner-all").removeClass("ui-state-active");	
	$("input[name='multiselect_affiliateWidgetContent']:checked").parent(".ui-corner-all").addClass("ui-state-active");
	$("input[name='multiselect_affiliateWidgetContentType']").parent(".ui-corner-all").removeClass("ui-state-active");	
	$("input[name='multiselect_affiliateWidgetContentType']:checked").parent(".ui-corner-all").addClass("ui-state-active");
	$("input[name='multiselect_languageID']").parent(".ui-corner-all").removeClass("ui-state-active");	
	$("input[name='multiselect_languageID']:checked").parent(".ui-corner-all").addClass("ui-state-active");
}
function grabButton()
{
	if($("#affiliateWidgetFormat").val()=="Large")
	generateWidget()
	return false;
}	
function regularPriceConstraints()
{
	//if($("#affiliateWidgetFormat").val()=="Large")
	generateWidget()
	//return false;
}