﻿                    

/// <reference path="jquery/jquery-1.3.2-vsdoc.js" />

$(window).unload(function() {
    if (document.getElementById('map_canvas') != null) {
        GUnload();
    }
});

$(document).ready(function() {
    //alert($("#fileInputUploader"));


    //alert(document.getElementById('fileInputUploader'));

    //alert(document.getElementById('fileInputUploader').style.visibility);
    //    alert($('#product_image_1').val());
    //    alert($('#product_image_2').val());
    //    alert($('#product_image_3').val());
    //if ($('#product_image_1').val() != "" )
    if ($('#product_image_1').val() != "" && $('#product_image_2').val() != "" && $('#product_image_3').val() != "" && $('#product_image_4').val() != "" && $('#product_image_5').val() != "") {

        //alert($("#divFileUpload"));
        $("#divFileUpload").css('visibility', 'hidden');
        $("#divFileUpload").css('display', 'none');
        //alert($("#divFileUpload").css('visibility'));

        //$("#fileInputUploader").hide();

    }




    // Make the first gallery image active 
    $("ul.gallery li:first").addClass("active");

    $.validator.addMethod('myEqual', function(value, element, param) {

        if (element.id == "phone") {
            if ($("#type-private")[0].checked) {
                return true;
            }
        }

        return param != value;
    }, "Dette feltet er påkrevet");

    $.validator.addMethod('checkUrl', function(value, element, param) {
        if ($("#url").val() != $("#url_hidden").val() && $("#url").val() != "") {
            var url_str = $("#url").val();
            str = url_str.search(/http:\/\//i);
            if (str == "-1" && url_str.length > 8) {
                $("#url").val("http://" + $("#url").val());
            }
            $("#url").rules("add", "url");

        } else {
            $("#url").rules("remove", "url");
        }

        return true;
    }, "Dette feltet er påkrevet");

    $.validator.addMethod('checkPrice', function(value, element, param) {
        if ($("#price").val() != $("#price_hidden").val()) {
            var number = $("#price").val();
            number = number.replace(/ /g, "");
            if (isNaN(number)) {
                return false;
            }
            else {
                return true;
            }
        } else {
            return true;
        }
    }, "Dette feltet er påkrevet");

    $("#search-input").focus(function() {
        if ($("#search-input").val() == $("#search-input-hidden").val()) {
            $("#search-input").val("");
        }
    });

    $("#search-input").blur(function() {
        if ($("#search-input").val() == "") {
            $("#search-input").val($("#search-input-hidden").val());
        }
    });

    // BLURRABLE BOXES
    // Blurrable boxes (.blurrable) are the boxes with a default value that disappears when you click in them.
    // They require a hidden input named ELEMENTID_hidden, containing the default value.

    // Clears the default value from the box if exists
    // Accepts jquery-wrapped field
    function clearDefaultValue(field) {
        var default_value = $("#" + field.id + "_hidden").val();
        if ($(field).val() == default_value)
            $(field).val("");
    }

    function reassignDefaultValue(field) {
        if ($(field).val() == "") {
            var default_value = $("#" + field.id + "_hidden").val();
            $(field).val(default_value);
        }
    }

    $(".blurrable").focus(function() {
        // When clicking inside a "blurrable" box, clear away the default value from it, if it's still there.
        clearDefaultValue(this);

    });

    $(".blurrable").blur(function() {
        // If nothing is entered in the "blurrable" box, set back the default value.
        reassignDefaultValue(this);
    });


    //VALIDATE MAIL FORM
    $("#form-mail-advertiser").validate({
        rules: {
            name: {
                required: true,
                myEqual: $("#name-hidden").val()
            },
            from: {
                required: true,
                myEqual: $("#from-hidden").val()
            },
            message: {
                required: true,
                myEqual: $("#message-hidden").val()
            }
        },
        /*errorPlacement: function(error, element) {
        error.css('display', 'none'); // Hide the "This field is required" labels.
        },*/
        submitHandler: function() {
            mailAdvertiser();
        }
    });


    //VALIDATE MAIL FORM
    $("#form-feedback").validate({
        rules: {
            message: {
                required: true,
                myEqual: $("#message-hidden").val()
            }
        },
        /*errorPlacement: function(error, element) {
        error.css('display', 'none'); // Hide the "This field is required" labels.
        },*/
        submitHandler: function() {
            feedbackAdvertiser();
        }
    });


    //VALIDATE REPORT FORM
    $("#form-report-ad").validate({
        rules: {
            report_ad_name: {
                required: true,
                myEqual: $("#report_ad_name_hidden").val()
            },
            report_ad_from: {
                required: true,
                myEqual: $("#report_ad_from_hidden").val()
            },
            report_ad_phone: {
                required: true,
                myEqual: $("#report_ad_phone_hidden").val()
            },
            report_ad_message: {
                required: true,
                myEqual: $("#report_ad_message_hidden").val()
            }
        },
        /*        errorPlacement: function(error, element) {
        error.css('display', 'none'); // Hide the "This field is required" labels.
        },*/

        submitHandler: function() {
            reportAd();
        }
    });

    //VALIDATE SHARE MAIL FORM
    $("#form-share-mail").validate({
        rules: {
            share_mail_from: {
                required: true,
                myEqual: $("#share_mail_from_hidden").val()
            },
            share_mail_name: {
                required: true,
                myEqual: $("#share_mail_name_hidden").val()
            }
        },
        submitHandler: function() {
            shareAd();
        }
    });

    //VALIDATE LOGIN
    $("#login-edit-ad").validate({
        submitHandler: function(form) {
            loginAndEditAd();
        }
    });

    $('input[name=type]').click(function() {
        if (($('input[name=type]:checked').val()) == "private") {
            $("#phone-private").show();
            $("#phone-company").hide();
            $("#company-name-tr").hide();

            $("#advertiser-url-tr").hide();
            $("#url").rules("remove", "url"); // Fix to prevent infinite loop bug in validation when trying to validate a hidden field

        } else if (($('input[name=type]:checked').val()) == "company") {
            $("#phone-company").show();
            $("#phone-private").hide();
            $("#company-name-tr").show();

            $("#advertiser-url-tr").show();
            $("#url").rules("add", "url");  // Fix to prevent infinite loop bug in validation when trying to validate a hidden field
        }
    });


    $(".edit-ad-form").validate({
        rules: {
            first_name: {
                required: true,
                myEqual: $("#first_name_hidden").val()
            },
            last_name: {
                required: true,
                myEqual: $("#last_name_hidden").val()
            },
            phone: {
                myEqual: $("#phone_hidden").val()
            },
            street: {
                required: true,
                myEqual: $("#street_hidden").val()
            },
            password: {
                required: true,
                myEqual: $("#password_hidden").val(),
                minlength: 6
            },
            password_confirm: {
                required: true,
                myEqual: $("#password_confirm_hidden").val(),
                minlength: 6,
                equalTo: "#password"
            },
            title: {
                required: true,
                myEqual: $("#title_hidden").val()
            },
            description: {
                required: true,
                myEqual: $("#description_hidden").val()
            },
            price: {
                checkPrice: $("#price_hidden").val()
            },
            url: {
                checkUrl: $("#url_hidden").val()
            }
        },
        /*errorPlacement: function(error, element) {
        error.css('display', 'none'); // Hide the "This field is required" labels.
        },*/
        focusInvalid: true,
        submitHandler: function(form) {

            // Clear out the default values from optional fields
            clearDefaultValue($("#company_name").get(0));
            clearDefaultValue($("#url").get(0));
            clearDefaultValue($("#phone").get(0));
            clearDefaultValue($("#price").get(0));

            // Strip spaces from price
            $("#price").val($("#price").val().replace(" ", ""));

            var geocoder = new GClientGeocoder();
            geocoder.getLocations($("#street").val() + ',' + $("#MarketCity").val() + ',' + $("#MarketCountry").val(),
            function(response) {

                if (response && response.Status.code == 200 && response.Placemark[0].AddressDetails.Accuracy >= 5) {
                    var place = response.Placemark[0];
                    $("#latitude").val(place.Point.coordinates[1]);
                    $("#longitude").val(place.Point.coordinates[0]);
                    form.submit();
                }
                else {
                    $("#latitude").val(0);
                    $("#longitude").val(0);
                    form.submit();
                }
            });
        }


    });

    $('#GmapMaximize').click(function() {
        LoadGMap("on");
    });

    $('#GmapMinimize').click(function() {
        LoadGMap("off");
    });

    function Set_Cookie(name, value, expires, path, domain, secure) {
        var today = new Date();
        today.setTime(today.getTime());

        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date(today.getTime() + (expires));

        document.cookie = name + "=" + escape(value) +
            ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ((secure) ? ";secure" : "");
    }


    function LoadGMap(GmapOn) {
        if (GmapOn == "off") {
            document.getElementById('linksWithGmap').style.width = '497px';
            document.getElementById('GmapMaximize').style.display = 'block';
            document.getElementById('GmapMinimize').style.display = 'none';
            document.getElementById('map_canvas').style.display = 'none';
            document.getElementById('shadow_map').style.display = 'none';
        }
        else {
            document.getElementById('linksWithGmap').style.width = '636px';
            document.getElementById('GmapMaximize').style.display = 'none';
            document.getElementById('GmapMinimize').style.display = 'block';
            document.getElementById('map_canvas').style.display = 'block';
            document.getElementById('shadow_map').style.display = 'block';
        }

        Set_Cookie('GoogleMapCookie', GmapOn, 365, '/', document.getElementById('DomainName').value, '');
    }




    function RenderCompanyList() {
        $("#CompanyListDiv").load('/MarketPlace/CompanyList/1');
    }


    $('[class^=print]').click(function() {

        var printWin = window.open("", "printWindow");

        if ($(".galleria_wrapper")[0] != null) {
            printWin.document.write($(".galleria_wrapper")[0].innerHTML);
            printWin.document.write("<br />");
        }

        if ($("#links")[0] != null) {
            printWin.document.write($("#links")[0].innerHTML);
            printWin.document.write("<br />");
        }

        if ($("#item-info")[0] != null) {
            printWin.document.write($("#item-info")[0].innerHTML);
            printWin.document.write("<br />");
        }

        if ($(".phone")[0] != null) {
            printWin.document.write("Phone No. : " + $(".phone")[0].innerHTML);
        }

        if (window.ActiveXObject) {
            printWin.location.reload();
        }

        printWin.window.print();
        return false;
    });

    $('[class^=Companyprint]').click(function() {

        var printWin = window.open("", "printWindow");

        if ($("#LogoImageAnchor")[0] != null) {
            printWin.document.write($("#LogoImageAnchor")[0].innerHTML);
            printWin.document.write("<br />");
        }

        if ($("#HeadImageDiv")[0] != null) {
            printWin.document.write($("#HeadImageDiv")[0].innerHTML);
            printWin.document.write("<br />");
        }

        if ($("#TemplateText")[0] != null) {
            printWin.document.write($("#TemplateText")[0].innerHTML);
        }


        if (window.ActiveXObject) {
            printWin.location.reload();
        }

        printWin.window.print();
        return false;
    });


    //TOGGLE AD DETAILS SERVICES
    $('[class^=toggle-item]').hide();
    $('[class^=service]').click(function() {
        $('[class^=toggle-item]').hide();
        var $this = $(this);
        var x = $this.attr("className");
        $('.toggle-item-' + x).toggle();
        //$.scrollTo('#ad-services');
        var pos = $('#ad-services').position();
        window.scrollTo(0, pos.top);
        window.scrollBy(0, -150);
        return false;
    });
    $('#fileInput').click(
    function() {
        alert('click');
    }
    )

    $('#fileInput').uploadify({
        'uploader': '/Scripts/jquery/uploadify/uploadify.swf',
        'cancelImg': '/Content/Graphics/cancel.png',
        'buttonImg': "/Content/Graphics/image_upload.gif",
        'auto': true,
        'folder': '/Content/Uploads',
        'script': '/MarketPlace/UploadImage',
        'onComplete': function(event, queueID, fileObj, response, data) {

            if (response.toString() != "No Files") {
                $("#product-images").append("<li><a class='image' href='/Content/Uploads/" + response + "'><img src='/Content/Uploads/" + response + "' alt='' /></a><a href='' class='delete' onclick=\"deleteImage(this, '" + response + "');return false;\">Ta bort</a></li>");
                if ($('#product_image_1').val() == "") {
                    $('#product_image_1').val(response);
                }
                else if ($('#product_image_2').val() == "") {
                    $('#product_image_2').val(response);
                }
                else if ($('#product_image_3').val() == "") {
                    $('#product_image_3').val(response);
                }
                else if ($('#product_image_4').val() == "") {
                    $('#product_image_4').val(response);
                }
                else if ($('#product_image_5').val() == "") {
                    $('#product_image_5').val(response);
                }

                //if ($('#product_image_1').val() != "" && $('#product_image_2').val() != "" && $('#product_image_3').val() != "") {
                if ($('#product_image_1').val() != "" && $('#product_image_2').val() != "" && $('#product_image_3').val() != "" && $('#product_image_4').val() != "" && $('#product_image_5').val() != "") {
                    $("#fileInputUploader").hide();
                }

                //Initialize lightBox for Ajax content
                $("#product-images .image").lightBox(); // Select all links in the page
            }
            else
                alert("Please select valid image file.");
        }
    });

    // LightBox
    $("#product-images .image").lightBox();

    //Click on name
    $("#show-mail-advertiser").click(function() { $(".toggle-item-service1").show(); $(".toggle-item-service2").hide(); $(".toggle-item-service3").hide(); $.scrollTo("#form-mail-advertiser"); })

    $(".graphicalAd").lightBox();

});

//IMAGE GALLERY
//jQuery(function($) { $('.gallery').galleria(); });

jQuery(function($) {

   // $('.gallery_demo_unstyled').addClass('gallery_demo'); // adds new class name to maintain degradability

$('ul.gallery').galleria({
        history: false, // activates the history object for bookmarking, back-button etc.
        clickNext: false, // helper for making the image clickable
        insert: '#main_image', // the containing selector for our main image
        onImage: function(image, caption, thumb) { // let's add some image effects for demonstration purposes

            // fade in the image & caption
            image.css('display', 'none').fadeIn(1000);
            
        
            
            caption.css('display', 'none').fadeIn(1000);

            // fetch the thumbnail container
            var _li = thumb.parents('li');

            // fade out inactive thumbnail
            _li.siblings().children('img.selected').fadeTo(500, 0.3);

            // fade in active thumbnail
            thumb.fadeTo('fast', 1).addClass('selected');

            // add a title for the clickable image
            image.attr('title', 'Next image >>');
        },
        onThumb: function(thumb) { // thumbnail effects goes here

            // fetch the thumbnail container
            var _li = thumb.parents('li');

            // if thumbnail is active, fade all the way.
            var _fadeTo = _li.is('.active') ? '1' : '0.3';

            // fade in the thumbnail when finnished loading
            thumb.css({ display: 'none', opacity: _fadeTo }).fadeIn(1500);

            // hover effects
            thumb.hover(
					function() { thumb.fadeTo('fast', 1); },
					function() { _li.not('.active').children('img').fadeTo('fast', 0.3); } // don't fade out if the parent is active
				)
        }
    });
});



function mailAdvertiser() {
    // create a JSON objects
    var mail = {
        adId: $("#mail-advertiser-id").val(),
        name: $("#name").val(),
        email: $("#from").val(),
        phone: $("#phone").val(),
        message: $("#message").val()
    }

    //Post the form
    $.post(
        "/MarketPlace/MailAdvertiser",
        mail,
        function(data) {
            if (data == "OK") {
                //SHOW THANKS
                $('.toggle-item-service1').toggle();
                $('#mail-thanks').css('display', 'block');
                $("#mail-thanks").fadeOut(5000);

                //Clear the form
                $("#adId").val("");
                $("#name").val("");
                $("#from").val("");
                $("#phone").val("");
                $("#message").val("");
            }
            else {
                $('.toggle-item-service1').toggle();
                $('#error-services').css('display', 'block');
                $("#error-services").fadeOut(7000);

                //Clear the form
                $("#adId").val("");
                $("#name").val("");
                $("#from").val("");
                $("#phone").val("");
                $("#message").val("");
            }
        },
        "json"
    );
    }

function loginAndEditAd() {
    // create a JSON objects
    var mail = {
        adId: $("#edit-ad-id").val(),
        email: $("#edit-mail").val(),
        password: $("#edit-password").val()
    }

    //Post the form
    $.post(
    "/MarketPlace/Login",
    mail,
    function(data) {
    if (data == "OK") {
            // SHOW THANKS
            window.location = "/MarketPlace/EditAd/" + $("#edit-ad-id").val();
        }
        else {
            $("#loginError").show();
        }
    },
    "json"
);
}


function reportAd() {
    // create a JSON objects
    var mail = {
        adId: $("#report_ad_id").val(),
        name: $("#report_ad_name").val(),
        email: $("#report_ad_from").val(),
        phone: $("#report_ad_phone").val(),
        message: $("#report_ad_message").val()
    }
    
    //Post the form
    $.post(
    "/MarketPlace/ReportAd",
    mail,
    function(data) {
        if (data == "OK") {
            $('.toggle-item-service3').toggle();
            $('#report-thanks').css('display', 'block');
            $("#report-thanks").fadeOut(5000);

            //Clear the form
            $("#report-ad-name").val("");
            $("#report-ad-from").val("");
            $("#report-ad-phone").val("");
            $("#report-ad-message").val("");
        }
        else {
            $('.toggle-item-service3').toggle();
            $('#error-services').css('display', 'block');
            $("#error-services").fadeOut(7000);            

            //Clear the form
            $("#report-ad-name").val("");
            $("#report-ad-from").val("");
            $("#report-ad-phone").val("");
            $("#report-ad-message").val("");
        }

    },
    "json"
    );
}

function feedbackAdvertiser() {
    // create a JSON objects
    var mail = {
        message: $("#message").val()
    }

    //Post the form
    $.post(
        "/MarketPlace/feedbackAdvertiser",
        mail,
        function(data) {
            if (data == "OK") {
                //SHOW THANKS
                $('#feedback-mail-thanks').css('display', 'block');
                $("#feedback-mail-thanks").fadeOut(5000);

                //Clear the form
                $("#message").val("");
            }
            else {
                $('#feedbacl-error-services').css('display', 'block');
                $("#feedbacl-error-services").fadeOut(7000);

                //Clear the form
                $("#message").val("");
            }
        },
        "json"
    );
}

function shareAd() {
    
    // create a JSON objects
    var mail = {
        adId: $("#share-mail-id").val(),
        email: $("#share_mail_from").val(),
        name: $("#share_mail_name").val(),
        message: $("#share-mail-message").val()
    }

    $.post(
    "/MarketPlace/ShareAd",
    mail,
    function(data) {
        //SHOW THANKS
        if (data == "OK") {
            $('#form-share-mail').fadeOut("fast",
       function() {
           $('#share-thanks').css('display', 'block');
           $("#share-thanks").fadeOut(5000,
                function() {
                    //Clear the form
                    $("#share_mail_from").val($("#share_mail_from_hidden").val());
                    $("#share_mail_name").val($("#share_mail_name_hidden").val());
                    $("#share-mail-message").val("");
                    $('#form-share-mail').fadeIn(1000);
                });
       });
        }
        else {
            $('#form-share-mail').fadeOut("fast");
            $('#error-share-mail').css('display', 'block');
            $("#error-share-mail").fadeOut(7000, function() { $('#form-share-mail').fadeIn(1000); });
            //Clear the form
            $("#share_mail_from").val($("#share_mail_from_hidden").val());
            $("#share_mail_name").val($("#share_mail_name_hidden").val());
            $("#share-mail-message").val("");
        }
    },
    "json"
    );
}

function deleteImage(item, path) {
    var check = confirm("Är du säker?");

    if (check) {
        $(item).parent().fadeOut("slow");
        if ($('#product_image_1').val() == path) {
            $('#product_image_1').val("");
        }
        else if ($('#product_image_2').val() == path) {
            $('#product_image_2').val("");
        }
        else if ($('#product_image_3').val() == path) {
            $('#product_image_3').val("");
        }
        else if ($('#product_image_4').val() == path) {
            $('#product_image_4').val("");
        }
        else if ($('#product_image_5').val() == path) {
            $('#product_image_5').val("");
        }

        if ($('#product_image_1').val() == "" || $('#product_image_2').val() == "" || $('#product_image_3').val() == "" || $('#product_image_4').val() == "" || $('#product_image_5').val() == "") {

            $("#fileInputUploader").show();
            $("#divFileUpload").css('visibility', 'visible');
            $("#divFileUpload").css('display', 'block');
        }
    }
}

function focusInput(inputObj,defaultValue) {
    $(inputObj).addClass("over");
    if ($(inputObj).val() == defaultValue) {
        $(inputObj).val("");
    }
}

function blurInput(inputObj,defaultValue) {
    $(inputObj).removeClass("over");
    if ($(inputObj).val() == "") {
        $(inputObj).val(defaultValue);
    }
}

function addToFavorites() {
    var url = location.href;
    var title = document.title;

    if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(title, url, "");
    } else if (window.external) { // IE Favorite
        window.external.AddFavorite(url, title);
    }
    else if (window.opera && window.print) { // Opera Hotlist
        return true;
    }
}

function forgotPassword(id){
        // create a JSON objects
    var mail = {
        id: id
    }
    
    $.post(
    "/MarketPlace/SendResetPasswordEmail",
    mail,
    function(data) {
        //SHOW THANKS
        if (data == "OK") {
            $("#login-edit-ad").hide();
            $("#forgot-password-default").hide();
            $("#forgot-password-success").show();
        }
        else {
            $("#login-edit-ad").hide();
            $("#forgot-password-default").hide();
            $("#forgot-password-error").show();
        }
    },
        "json"
    );



}


