﻿/// <reference path="jquery-1.3.1.js" />

function EcoLabelLink(linkvalue) {
    if (linkvalue != "") {
        document.location = linkvalue;
    }
}

//Render the content part (between the first and last <!--Content--> comment)of a page into a div 
function renderPageIntoContainerCallback(response, a, b, options) {
    var responseText = response;
    var cleanedResponseText = responseText.substring(responseText.indexOf('<!--Content-->'), responseText.lastIndexOf('<!--Content-->'));

    if (options.indicator) options.indicator.hide();

    //    Ext.select(".button", false, options.targetContainer).each(function() { imageButton(this.dom); });
    //    Ext.select(".buttonLight", false, options.targetContainer).each(function() { imageButton(this.dom); });

    //    if (Ext.isIE6) {
    //        Ext.select(".alphaImage").each(function() { alphaImage(this.dom); });
    //        Ext.select("img").each(function() { if (this.dom.src && this.dom.src.indexOf(".png") > 0) alphaImage(this.dom); });
    //    }

    if (options.callAfterSuccess)
        options.callAfterSuccess();
}
var timeout;

function renderQueueManager(container) {
    var index = jQuery.inArray(container, runningRenderContainers);
    if (index > -1) {
        //Abort the request and remove it from the queue
        runningRenderRequests[index].abort();
        runningRenderContainers = runningRenderContainers.splice(index,1);
        runningRenderRequests = runningRenderRequests.splice(index, 1);
    }
}

function renderQueueManagerAbortAll() {
    for (var x = 0; x < runningRenderRequests.length; x++) {
        runningRenderRequests[x].abort();
    }
    runningRenderContainers = new Array();
    runningRenderRequests = new Array();
}

var runningRenderContainers = new Array();
var runningRenderRequests = new Array();
function renderPageIntoContainer(pageUrl, container, callback, delay, indicatorElement) {
    //If there is a request running for the same container it should be aborted. To handle this i need to have a manual queue.
   renderQueueManager(container);

   var ajaxRequest = $.ajax({
       url: pageUrl,
       cache: true,
       container: container,
       complete: function(XMLHttpRequest, textStatus) {
           renderQueueManager(this.container); //When the request is finished it should be removed from the queue
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
         //  alert("textStatus: " + textStatus + "\n\n\n errorTrown: " + errorThrown);
           // typically only one of textStatus or errorThrown 
           // will have info
           this; // the options for this ajax request
       }
        ,
       success: function(html) {
           newHtml = $(html).html();
           if (newHtml != $(container).html()) {
               if (newHtml.indexOf('class="resultList"') == -1 && newHtml.indexOf('class=resultList') == -1) {
                   $(container).slideUp('fast', function() {
                       $(this).parent().hide();
                   });
               } else {
                   $(container).parent().show();
                   $(container).show();
               }
               $(container).html(newHtml);
               if ($(".partialResultCount").size() > 0) {
                   var resultCount = 0;
                   $(".partialResultCount").each(
                            function() {
                                resultCount += parseInt($(this).html());
                            }
                        );
                   $(".resultCount").html(resultCount);
               }
               else {
                   $(".resultCount").html("0");
               }
           }
       }
   });
   
    runningRenderContainers.push(container);
    runningRenderRequests.push(ajaxRequest);
}

function renderControl(control, container, parameters, callback, delay, indicator) {
    if (indicator) indicator.show();
    renderPageIntoContainer(baseUrl + "AJAX/RenderControl/?control=" + control + "&" + parameters + "&originator=" + window.location.pathname, container, callback, delay, indicator);
}

function showAllResults(containerId, queryUrl) {
    if ($('.liveSearchTextBox').size == 1 && $('.liveSearchTextBox').val().length > 1) queryUrl += "&query=" + $('.liveSearchTextBox').val();
    if ($('#' + containerId).size == 1)
        queryUrl += "&rootPage=" + $('#' + containerId).closest(".rootPage").val();
    
    renderControl("LiveSearchPart", "#" + containerId, queryUrl, null, 5);
   }

   function renderPageIntoContainerRetailers(pageUrl, container, callback, delay, indicatorElement) {
   	//Ext.Ajax.on("abort", renderPageFailure, null, { indicator: indicatorElement });
   	if (delay) {
   		window.clearTimeout(timeout);
   		timeout = window.setTimeout(function() {
   			$(container).load(pageUrl + "#content", null, callback);
   		}, delay);
   	} else {
   		$(container).load(pageUrl + "#content", null, callback);
   	}
   }

   function renderControlRetailers(control, container, parameters, callback, delay, indicator) {
   	if (indicator) indicator.show();
   	renderPageIntoContainerRetailers(baseUrl + "AJAX/RenderControl?control=" + control + "&" + parameters + "&originator=" + document.location, container, callback, delay, indicator);
   }

var oldText="";
//Enable all livesearch on the page
//$(document).ready(function() {
//    $(".liveSearchTextBox").keyup(function() {
//        if (oldText != $(this).val()) {
//            //Abort all queues
//            renderQueueManagerAbortAll();
//            var srcElement = $(this);
//            var searchString = encodeURIComponent(srcElement.val());
//            if (srcElement.val().length > 0 && this.keyCode != 27) {
//                //Only react when the text actually changes

//                if (pageTracker != null) pageTracker._trackPageview("/ajax/search/" + searchString);


//                //TODO: this may need to be more sequential, perhaps each callback will call the next or group them 2 by 2
//                if ($("#retailerResult").size() > 0) renderControl("LiveSearchPart", "#retailerResult", 'query=' + searchString + "&targetContainer=" + "retailerResult" + "&pagetypeId=18&itemControl=retailer&displaymode=Text&maxCount=5&title=Butiker&callingPageId=" + $("#pageId").val(), null, 50);
//                if ($("#productResult").size() > 0) renderControl("LiveSearchPart", "#productResult", 'query=' + searchString + "&onlyPageName=true&targetContainer=" + "productResult" + "&pagetypeId=23&itemControl=product&displaymode=Small&maxCount=5&title=Produkter&callingPageId=" + $("#pageId").val(), null, 50);
//                if ($("#b2bProductResult").size() > 0) renderControl("LiveSearchPart", "#b2bProductResult", 'query=' + searchString + "&targetContainer=" + "productResult" + "&pagetypeId=23&itemControl=product&displaymode=Text&maxCount=5&title=Produkter&callingPageId=" + $("#pageId").val(), null, 50);
//                if ($("#colorResult").size() > 0) renderControl("LiveSearchPart", "#colorResult", 'query=' + searchString + "&targetContainer=" + "colorResult" + "&pagetypeId=24&itemControl=color&displaymode=Small&maxCount=5&title=Kulörer&callingPageId=" + $("#pageId").val(), null, 50);
//                if ($("#instructionResult").size() > 0) renderControl("LiveSearchPart", "#instructionResult", 'query=' + searchString + "&targetContainer=" + "instructionResult" + "&pagetypeId=26&itemControl=instruction&displaymode=Small&maxCount=5&title=Arbetsråd&callingPageId=" + $("#pageId").val(), null, 50);
//                if ($("#photoResult").size() > 0) renderControl("LiveSearchPart", "#photoResult", 'query=' + searchString + "&targetContainer=" + "photoResult" + "&pagetypeId=25&itemControl=photo&displaymode=Small&maxCount=5&title=Bilder&callingPageId=" + $("#pageId").val(), null, 50);
//                if ($("#freetextResult").size() > 0) renderControl("LiveSearchPart", "#freetextResult", 'query=' + searchString + "&targetContainer=" + "freetextResult" + "&pagetypeId=37&itemControl=freetextSearch&displaymode=Text&maxCount=5&title=Fritext&callingPageId=" + $("#pageId").val(), null, 50);
//                if ($("#documentResult").size() > 0) renderControl("LiveSearchPart", "#documentResult", 'query=' + searchString + "&targetContainer=" + "documentResult" + "&pagetypeId=35&itemControl=attachment&displaymode=Small&title=Dokument&callingPageId=" + $("#pageId").val(), null, 50);
//                if ($("#productAttachmentResult").size() > 0) renderControl("LiveSearchPart", "#productAttachmentResult", 'query=' + searchString + "&targetContainer=" + "productAttachmentResult" + "&pagetypeId=35&itemControl=productattachment&displaymode=Small&title=Produkter&callingPageId=" + $("#pageId").val(), null, 50);
//                
//                //TODO: Freetext may required a selection of pagetypes instead of just standard
//            } else {
//                //Hide all results
//                $(".subContentBar .resultContent:not(.nonsearchable)").slideUp('fast', function() { $(this).parent().hide(); });
//            }
//        }
//        oldText = $(this).val();
//    });
//});

//Enable addcart functionality
$(document).ready(function() {

    $(".cartButtons").find(".addToCart").click(function() {
        //Slide from caller (this) to the toolbox item
        //TODO: animation that perhaps switches the icon to an animated one?
        $(this).parent().removeClass("add");
        $(this).parent().addClass("remove");
        $(this).css("position", "");


        $(".toolBox").addClass("toolBoxInUse");
        //        $(this).css("position", "");
        //        
        //        var leftSourcePosition = $(this).position().left;
        //        var topSourcePosition = $(this).position().top;
        //        
        //        var leftTarget = $('.toolBox').position().left;
        //        var topTarget = $('.toolBox').position().top;
        //        $(this).css("position", "absolute");
        //        $(this).css("left", leftSourcePosition);
        //        $(this).css("top", topSourcePosition);
        //        
        //        $(this).animate({ left: leftTarget, top: topTarget }, 500, 'swing', function() {
        //          
        //        });
    });

    $(".cartButtons").find(".removeFromCart").click(function() {
        $(this).parent().addClass("add");
        $(this).parent().removeClass("remove");
        $(this).css("position", "");

        //TODO: only do this if the last item from the cart is removed
        $(".toolBox").removeClass("toolBoxInUse");

        //Slide from the toolbox item to the caller
        //        $(this).css("position", "");
        //        
        //        var leftSourcePosition = $(".toolBox").position().left;
        //        var topSourcePosition = $(".toolBox").position().top;
        //        var leftTarget = $(this).position().left;
        //        var topTarget = $(this).position().top;

        //        $(this).css("position", "absolute");
        //        $(this).css("left", leftSourcePosition);
        //        $(this).css("top", topSourcePosition);

        //        $(this).animate({ left: leftTarget, top: topTarget }, 500, 'swing', function() {
        //         
        //        });
    });

});

function searchKeyPress(event, source) {

//    if ($(source).attr("id") == "field") {
//        $("#s").val($(source).val());
//        $("#s").trigger("keyup");
//    }
//    else
     $("#field").val($(source).val());

    if (event.keyCode == 13)
        $('.searchLink').click(); return false;
}

function combinePDFs(element) {
    $("#media").val(generateCombinePDFsLink(element));
    //alert($("#media").val());
    $("#mediaForm").submit();
    //window.open(element.href + generateCombinePDFsLink(element), "", "", "");
}

var ajaxBaseUrl = "/Services/Toolbox.asmx/";

function emailCombinedPDFs(element, email) {
      
      var url = generateCombinePDFsLink(element);
      $.ajax({
          type: "POST",
          data: "{'url':" + url + ",'mailAddress':'"+email+"'}",
          dataType: "json",
          url: ajaxBaseUrl + "SendPDFMail",
          contentType: "application/json; charset=utf-8"
      });
}

function generateCombinePDFsLink(element) {
    var combinedString = "";
    var count = 0;
    $(".attachmentSelector").each(function() {

        if (this.checked) {
            combinedString += $(this).prev(".download").attr("rel");
            combinedString += ",";
            count++;
        }
    }
    );
    //Trim the last comma
    if (combinedString.indexOf(",", 0) > -1)
        combinedString = combinedString.substring(0, combinedString.length - 1);
    return combinedString;
}

function popup(url, width, height, name) {
    window.open(url, name, 'height=' + height + ',width=' + width + ',toolbar=0,menubar=0,location=0,resizable=0');
}

//Functionality for the studio window
var tinterPopupWindow = null;
function openTinter(baseUrl, lang, context) {
    if (context != '1' && context != '2') {
        context = '0';
    }
    var tinterUrl = baseUrl + lang + '/?context=' + context;
    try {
        var matches = window.location.href.match(/resetpassword=(.*?)&token=(.*)/);
        if (matches.length == 3) {
            tinterUrl = tinterUrl + '&u=' + matches[1] + '&token=' + matches[2];
        }
    } catch (e) { }

    if (tinterPopupWindow == null || tinterPopupWindow.closed) {
        tinterPopupWindow = window.open(tinterUrl, '', "fullscreen=yes,location=no,menubar=no,resizing=yes,scrollbars=no");
    }
    else {
        if (tinterPopupWindow.focus) {
            tinterPopupWindow.focus();
        }
    }
}

function openslideshow() {
    $(".lightbox.listItem.first").click();
    //$.fancybox.next();
}