﻿Event.observe(window, 'load', adjustComponentPosition, false);
Event.observe(window, 'load', loadingLogic, false);

function loadingLogic() {
    var recipeIds = $$(".recipeUniqueId");
    var recipeId = recipeIds[0].value;            
    // default loading indicator   
    var indicators = $$(".recipeContainsImageIndicator");
    var indicator = indicators[0];           
    if (indicator.value) {
        // delay 3.5 seconds to wait for the page to complete loading.
        var thefunction = "getRecipeImages(" + recipeId + ")";
        var fade=setTimeout(thefunction,1500);
        //getRecipeImages(recipeId);       
    } 
}  
function adjustComponentPosition() {
    var elementAbove = $("recipeTitle");
    var elementToAjdust = $("recipeBody");
    var recipeNavLink = $("recipeNaveLink");
    if (elementToAjdust && elementAbove) {
       var height = elementAbove.getHeight();
       height = height / 2;
       height = height + recipeNavLink.getHeight();
       elementToAjdust.style.top = -height + "px";
    }    
}

function getRecipeImages(id) {
    if ($("recipeImageCenter").visible()) {
        return;
    }
    var elementToUpdate = $("recipeImageCenter");
    var elementToOverride = $("recipeTypedCenter");
    if (! elementToOverride.visible()) {
        // if the recipe story is not visible then it must be the image center view
        // get the element of the image center view.     
        elementToOverride =  $("recipeStoryCenter");
    }    
    var url = "action.asmx/recipe_GetImagePaths";
    if ($$(".recipeShareWrapper")) {
        url = "publicAction.asmx/recipe_GetImagePaths";
    }
    
    var requestBody = "{id:" + id + "}";
    new Ajax.Request(url, {
        method: 'post',
        postBody: requestBody,
        contentType:'application/json; charset=utf-8',
        onSuccess: function(transport) {
            var returnObj = transport.responseJSON;
            if (returnObj && returnObj.d != null) {
                var returnString = returnObj.d;
                if (returnString.length <= 0) {
                    alert("Cannot retrive recipe images!");
                } else {
                    var recipeImages = returnString.split(/;/); 
                    $("recipeImages").Value = returnString;
                    $("recipeCurrentImgIndex").Value = 0;
                    var imgmap = recipeImages[$("recipeCurrentImgIndex").Value].split(/,/);
                    $("recipeCurrentImg").src = imgmap[1];                    
                    $("recipeImagePreviousButton").hide();                    
                    if (recipeImages.length <= 1) {
                        $("recipeImageNextButton").hide();
                    }
                    Effect.SlideUp(elementToOverride, {afterFinish: showImage});                    
                }
            } else{
                alert("Cannot retrive recipe images!");
            }
        },
        onFailure: function(transport) {
            alert("Cannot communicate with the site.  Try again later!  Thanks");
        }
    });
}

function nextRecipeImage() {
    var recipeImages =  $("recipeImages").Value.split(/;/); 
    var currentVal = $("recipeCurrentImgIndex").Value;
    if (recipeImages.length <= (currentVal + 1)) {
        return;
    }
    $("recipeCurrentImgIndex").Value = currentVal + 1;    
    var imgmap = recipeImages[currentVal + 1].split(/,/);    
    $("recipeCurrentImg").src = imgmap[1];
    if ( $("recipeCurrentImgIndex").Value >= recipeImages.length -1) {
        $("recipeImageNextButton").hide();
    } else {
        $("recipeImageNextButton").show();
    }
    if ($("recipeCurrentImgIndex").Value <= 0) {
        $("recipeImagePreviousButton").hide();
    } else {
        $("recipeImagePreviousButton").show();
    }
}

function previousRecipeImage() {
    var recipeImages =  $("recipeImages").Value.split(/;/); 
    var currentVal = $("recipeCurrentImgIndex").Value;
    if (currentVal <= 0) {
        return;
    }
    $("recipeCurrentImgIndex").Value = currentVal - 1;    
    var imgmap = recipeImages[currentVal -1].split(/,/);
    $("recipeCurrentImg").src = imgmap[1];
     if ( $("recipeCurrentImgIndex").Value >= recipeImages.length -1) {
        $("recipeImageNextButton").hide();
    } else {
        $("recipeImageNextButton").show();
    }
    if ($("recipeCurrentImgIndex").Value <= 0) {
        $("recipeImagePreviousButton").hide();
    } else {
        $("recipeImagePreviousButton").show();
    }
   
}

function showImage() {
    Effect.SlideDown("recipeImageCenter", {afterFinish: adjustImage});     
}
function adjustImage() {
    var imgWidth =  $("recipeCurrentImg").getWidth();
    var imgHeigh = $("recipeCurrentImg").getHeight();
    if ((imgHeigh / (1.0 * imgWidth)) > 1.07) {
        $("recipeCurrentImg").className = 'recipeImageHeight';
    } else {
         $("recipeCurrentImg").className = 'recipeImageWidth';
    }
}

function getTypedText(id) {
    if ($("recipeTypedCenter").visible()) {
        return;
    }
    var elementToUpdate = $("recipeTypedCenter");
    var elementToOverride =  $("recipeStoryCenter");
    // dont' need to request a copy from database since the data already here
    if (! elementToOverride.visible()) {
        // if the recipe story is not visible then it must be the image center view
        // get the element of the image center view.     
        elementToOverride =  $("recipeImageCenter");
    }
    Effect.SlideUp(elementToOverride, {afterFinish: showTypedText});
}
function showTypedText() {
    Effect.SlideDown("recipeTypedCenter"); 
}

function getStory(id) {
    if ($("recipeStoryCenter").visible()) {
        return;
    }
    var elementToUpdate = $("recipeStoryField");
    var elementToOverride = $("recipeTypedCenter");
    if (! elementToOverride.visible()) {
        // if the recipe story is not visible then it must be the image center view
        // get the element of the image center view.     
        elementToOverride =  $("recipeImageCenter");
    }
    var url = "action.asmx/recipe_GetStory";
    if ($$(".recipeShareWrapper")) {
        url = "publicAction.asmx/recipe_GetStory";
    }
    var requestBody = "{id:" + id + "}";
    new Ajax.Request(url, {
        method: 'post',
        postBody: requestBody,
        contentType:'application/json; charset=utf-8',
        onSuccess: function(transport) {
            var returnObj = transport.responseJSON;
            if (returnObj)
            {   
                var returnTxt = returnObj.d;
                if (returnTxt == null || returnTxt.length == 0) {
                    returnTxt = "[Edit]";
                }
                elementToUpdate.update(returnTxt);
                Effect.SlideUp(elementToOverride, {afterFinish: showStory});
            }
            else
            {
                alert("Cannot retrive recipe story!");
            }
        },
        onFailure: function(transport) {
            alert("Cannot communicate with the site.  Try again later!  Thanks");
        }
    });
    
}
function showStory() {
    Effect.SlideDown("recipeStoryCenter");    
}



function setMotif(recipeId, motifId) {
    var url = "action.asmx/recipe_UpdateMotif";
    var requestBody = "{id:" + recipeId + ", value:" +motifId + "}";
    new Ajax.Request(url, {
        method: 'post',
        postBody: requestBody,
        contentType:'application/json; charset=utf-8',
        onSuccess: function(transport) {
            if (transport.responseText.match(/true/))
            {   
                
                replacecssfile(motifId);
            }
            else
            {
                alert("Cannot cannot save motif!");
            }
        },
        onFailure: function(transport) {
            alert("Cannot communicate with the site.  Try again later!  Thanks");
        }
    });
    
}


function createcssfile(filename){
  var fileref=document.createElement("link");
  fileref.setAttribute("rel", "stylesheet");
  fileref.setAttribute("type", "text/css");
  fileref.setAttribute("href", "motifs/css/" + filename + ".css");
 return fileref
}

function replacecssfile(newfilename){
    var targetelement="link";
    var targetattr="href";
    var allsuspects=document.getElementsByTagName(targetelement);
    var motifName = new RegExp("motifs/css/[0-9]+\\.css");
    for (var i=allsuspects.length; i>=0; i--){
        var interestedElem = allsuspects[i];
        if (interestedElem) {
            var interetedElemtLink = interestedElem.getAttribute(targetattr)
            if (interetedElemtLink) {
                var m = interetedElemtLink.match(motifName);
                if (m != null) {
                    var newelement=createcssfile(newfilename)
                    interestedElem.parentNode.replaceChild(newelement, interestedElem);                    
                }
            }        
        }
    }
}

function showSaving() {
    var savingElement = $("ajaxSaving");
    savingElement.style.visibility="visible";
}
function hideSaving() {
    setTimeout(hideSavingBox,1000);              
}
function hideSavingBox() {
    var savingElement = $("ajaxSaving");
    savingElement.style.visibility="hidden";
}