var hotLinkHelper = {
    ajaxUrlLink: null,

    hotCache: {
        getLinkUrl: "",
        getImageUrl: "",
        getTimeOut: "3000"}
};

window.$ = jQuery;
var len = 0;
var id = 0;
var time = 3000;

function fadeEngine(x) {
    var y = x;
    if (x == len - 1) {
        y = 0;
    } else {
        y++;
    }
    $("#testimonial" + x).css("display", "none");
    $("#testimonial" + y).fadeIn("slow");
    setTimeout('fadeEngine(' + y + ')', hotLinkHelper.hotCache.getTimeOut);
}

function callLinks() {
    $('#hot-link').block('&nbsp;', {background : 'url(/html/image/load2.gif) no-repeat', height : '80px', width : '199px'});
    $.ajax({
        url: hotLinkHelper.hotCache.getLinkUrl,
        method:'post',
        dataType:'json',
        success: function(json) {
            time = json['timeout'];
            $("#iamgeDiv").html('<img src="' + hotLinkHelper.hotCache.getImageUrl + '/html/image/hot-link.jpg?ran=' + Math.random() + '" height="42px" width="153" >');
            $("#links").html('');
            for (var i in json) {
                $("#links").append('<div id="testimonial' + i + '" class="testimonial" style="display: none;">'
                        + json[i]['title']
                        + '&nbsp;<a href="' + json[i]['title_link'] + '">' + json[i]['link'] + '</a></div>');
                len ++;
            }
            $('#hot-link').unblock();
            fadeEngine(0);
        }
    });
}

function addnewFieldsLinks(idElem) {
    var newId = id;
    $("#" + idElem).append('<div id="hotCont' + newId + '" class="hotDivInp">' +
                           'Text: <input type="text" name="title_' + newId + '" calass="fieldHotLink" size="30">  &nbsp;&nbsp; ' +
                           'Link: <input type="text" name="title_link_' + newId + '" class="fieldHotLink" size="30"> ' +
                           '&nbsp;&nbsp;Link Title: <input type="text" name="link_' + newId + '" class="fieldHotLink" size="30">' +
                           '&nbsp;<input type="button" value="Delete" name="delete" onclick="deleteElement(\'hotCont' + newId + '\'); return false;"></div>');
    id++;
}

function callData(json) {

    $("#timeoutS").val(hotLinkHelper.hotCache.getTimeOut);

    $("#editLinks").html('');
    for (var i in json) {
        var newId = id;
        $("#editLinks").append('<div id="hotCont' + newId + '" class="hotDivInp">' +
                               'Text: <input type="text" name="title_' + newId + '" value="' + json[i]['title'] + '" class="fieldHotLink"  size="30"> &nbsp;&nbsp; ' +
                               'Link: <input type="text" name="title_link_' + newId + '" value="' + json[i]['title_link'] + '" class="fieldHotLink" size="30">' +
                               '&nbsp; &nbsp;Link Title: <input type="text" name="link_' + newId + '" value="' + json[i]['link'] + '" class="fieldHotLink" size="30">' +
                               '&nbsp;<input type="button" value="Delete" name="delete" onclick="deleteElement(\'hotCont' + newId + '\'); return false;"></div>');
        id++;
    }
}

function deleteElement(idElem) {
    var confirmationDel = window.confirm("Are you sure to remove this link?");
    if (confirmationDel) {
        $("#" + idElem).remove();
    }


}


function callValuesEdit() {

    $('#preferencesLinks').block('&nbsp;', {background : 'url(/html/image/load2.gif) no-repeat', height : '80px', width : '199px'});
    $.ajax({
        url: hotLinkHelper.hotCache.getLinkUrl,
        method:'get',
        dataType:'json',
        success: function(json) {
            $("#editLinks").html('');
            try {
                callData(json);
            } catch(e) {
                alert('Error call callData function.' + e);
            }
            $('#preferencesLinks').unblock();
        },
        error : function (errordata) {
            alert("Error load links from server. Details : " + errordata);
        }
    });
}

function post(aUrl, formId, onSuccess, onError) {
    var queryString = jQuery('#' + formId).formSerialize();
    var amp = '&';
    if (aUrl.charAt(aUrl.length - 1) == '&') {
        amp = '';
    }
    jQuery.ajax({
        url: aUrl,
        type: 'POST',
        data: queryString,
        dataType: 'json',
        timeout: 30000,
        async: false,
        error: function(data) {
            onError(data);
        },
        success: function(data) {
            onSuccess(data);
        }
    });
}
;

function saveHotLinks() {
    //    $('#hotFormId').block('&nbsp;', {background : 'url(/html/image/load2.gif) no-repeat', height : '80px', width : '199px'});
    var dd = $(':text');

    var error = '';
    var timeVar = $("#timeoutS").val();
    var pattern = '[^0-9]';

    if (timeVar.length == 0) {
        error = "Field 'Time out' must be not zero";
    }
    if ((timeVar.match(pattern) != null)) {
        error = "Field 'Time out' only: '1-9'";
    }

    /*if (timeVar.length == 0 && pattern.match(timeVar)) {
     error = "Enter valid time out";
     }*/

    dd.each(function() {
        var value = $(this).val();
        var classE = $(this).attr('class');

        if (value == '' && classE == 'fieldHotLink') {
            error = "Fill in all fields";

        }
    });
    if (error.length > 0) {
        $("#errorMessage").html('<div class="errorMessage"><h3 style="color:red;">' + error + '</h3></div>');
    } else {
        $('#action').val("action_save");
        $("#errorMessage").html('&nbsp;');
        error = '';

        document.getElementById('hotFormId').submit();
        //        post(hotLinkHelper.hotCache.getLinkUrl, 'hotFormId',
        //                function (data) {
        //                    callData(data);
        //                },
        //                function (errorData) {
        //  alert(errorData);
        //                });
    }
    //    $('#hotFormId').unblock();
}


function uploadFile() {

    if (isImageType()) {

        $("#errorMessage").html('&nbsp;');
        $('#uploadDiv').block('&nbsp;', {background : 'url(/html/image/load2.gif) no-repeat', height : '80px', width : '199px'});
        $('#uploadImggForm').ajaxSubmit(options());
    } else {
        $("#errorMessage").html("file is not selected or unsupported format");
    }


}

function options() {
    var opt = {
        url: hotLinkHelper.hotCache.getLinkUrl + '&random=' + new Date().toGMTString(),
        type: 'POST',
        dataType: 'json',
        success: function(json) {
            $("#errorMessage").html(json['error']);
            $('#fileImage').val("");
            $('#uploadDiv').unblock();
            previewImage();
        },
        error: function(h) {
            previewImage();
            $('#fileImage').val("");
            //$("#errorMessage").html("Error ...");
            $('#uploadDiv').unblock();


            //            for (var field in h) {
            //                alert('field:' + field + '. value:' + h[field]);
            //            }
        }
    };
    return opt;
}

function previewImage() {
    $("#previewImage").html('<img src="' + hotLinkHelper.hotCache.getImageUrl + '/html/image/hot-link.jpg?ran=' + Math.random() + '" height="42px" width="153" >');
}

function isImageType() {
    var elem = $("#fileImage").val();
    var lvalue = elem;
    if (lvalue.length == 0) {
        return false;
    }
    var extensions = [ 'JPG', 'JPEG', 'GIF', 'PNG' ];
    for (var i = 0; i < extensions.length; i++) {
        var ext = extensions[i];
        var pointIndex = lvalue.lastIndexOf(".") + 1;
        var extension = lvalue.substring(pointIndex, lvalue.length);
        if (ext == extension.toUpperCase()) {
            return true;
        }
    }
    return false;
}
