//my global var
var fall2012P3 = {};

//db var
fall2012P3.db;

//current id
fall2012P3.curentID = 0;

//cross browsers
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
// Moreover, you may need references to some window.IDB* objects:
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;

//setup database
fall2012P3.setupDB = function () {

    var fermieri = getLocalData();

    var request = indexedDB.open("FarmersDatabase", 1);

    request.onupgradeneeded = function (evt) {

        fall2012P3.db = evt.target.result;

        var objectStore = fall2012P3.db.createObjectStore("farmers", {
            keyPath: "id",
            autoIncrement: true
        });

        objectStore.createIndex("City", "City", {
            unique: false
        });

        objectStore.createIndex("Zip", "Zip", {
            unique: false
        });

        //add data to the store
        for (var i = 0; i < fermieri.length; i++) {
            objectStore.add(fermieri[i]);
        }

    };

    request.onsuccess = function (evt) {

        fall2012P3.db = request.result;

        fall2012P3.onSuccessZip();

        document.getElementById("locationDiv").style.display = 'none';
        document.getElementById("resetDiv").style.display = 'none';
        document.getElementById("mapDiv").style.display = 'none';
        document.getElementById("searchDiv").style.display = '';
    };

    request.onerror = function (evt) {
        alert(evt.target.errorCode);
    };
}


//set first launch in local storage
fall2012P3.setFirst = function () {
    localStorage.first = "yes";
}

//retreive farmers on the search div
fall2012P3.searchFarmer = function () {
    var transaction = fall2012P3.db.transaction('farmers', 'readonly');
    var objectStore = transaction.objectStore("farmers");

    var output = document.getElementById("outcome");
    output.innerHTML = "";

    var n = document.getElementById('searchFarmer').value;

    if (isNaN(n)) {
        var index = objectStore.index("City");
        var x = String(fall2012P3.trim(n));
        var t = fall2012P3.toTitleCase(x);
        var singleKeyRange = IDBKeyRange.only(t);
        index.openCursor(singleKeyRange).onsuccess = function (event) {
            var cursor = event.target.result;
            if (cursor) {

                fall2012P3.curentID = cursor.value.ID;

                output.innerHTML += '<div class = "inside">' +
                '<input type="radio" name="requestRadio" value="' +
                cursor.value.ID + '" onclick="fall2012P3.setID(this.value)">' +
                '<span style="font-weight: bold;">' + cursor.value.MarketName + '</span>' +
                ", " + cursor.value.Street + ", " +
                cursor.value.City + ", " + cursor.value.State + ", " + cursor.value.Zip + " " +
                '</div>' + '<hr class="linie"/>';

                cursor.continue();

            } else {
                document.getElementById("searchDetails").disabled = true;
            }
        };

    } else {
        var index = objectStore.index("Zip");
        var singleKeyRange = IDBKeyRange.only(String(n));
        index.openCursor(singleKeyRange).onsuccess = function (event) {
            var cursor = event.target.result;
            if (cursor) {
                output.innerHTML += '<div class = "inside">' +
			'<input type="radio" name="requestRadio" value="' +
			cursor.value.ID + '" onclick="fall2012P3.setID(this.value)">' +
			'<span style="font-weight: bold;">' + cursor.value.MarketName + '</span>' +
			", " + cursor.value.Street + ", " +
			cursor.value.City + ", " + cursor.value.State + ", " + cursor.value.Zip + " " +
			'</div>' + '<hr class="linie"/>';

                fall2012P3.curentID = cursor.value.ID;

                cursor.continue();
            } else {
                document.getElementById("searchDetails").disabled = true;
            }
        };
    }

}

//remove white spaces
fall2012P3.trim = function (str) {
    var arie = str.split(" ");
    var nArie = [];
    var nStr = "";

    for (var i = 0; i < arie.length; i++) {
        if (arie[i] != '') {
            nArie.push(arie[i]);
        }
    }

    if (nArie.length === 1) {
        nStr = String(nArie[0]);
    } else if (nArie.length === 2) {
        nStr = String(nArie[0]) + " " + String(nArie[1]);
    } else if (nArie.length === 3) {
        nStr = String(nArie[0]) + " " + String(nArie[1]) + " " + String(nArie[3]);
    } else {
        nStr = "";
    }

    return nStr;
}

//caps every word
fall2012P3.toTitleCase = function (str) {
    return str.replace(/\w\S*/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

//open database on init
fall2012P3.openDB = function () {
    var request = indexedDB.open("FarmersDatabase");
    request.onsuccess = function (evt) {
        fall2012P3.db = request.result;
        fall2012P3.onSuccessZip();
    };

    request.onerror = function (evt) {
        alert(evt.target.errorCode);
    };

}

//initiate function
fall2012P3.init = function () {

    document.getElementById("searchDetails").disabled = true;

    if (localStorage.first) {
        document.getElementById("locationDiv").style.display = 'none';
        document.getElementById("mapDiv").style.display = 'none';
        document.getElementById("resetDiv").style.display = 'none';
        document.getElementById("searchDiv").style.display = '';
        fall2012P3.openDB();
    } else {
        document.getElementById("searchDiv").style.display = 'none';
        document.getElementById("mapDiv").style.display = 'none';
        document.getElementById("locationDiv").style.display = '';
        document.getElementById("resetDiv").style.display = 'none';
    }
}

//get farmers to display based on zip
fall2012P3.onSuccessZip = function () {
    fall2012P3.getZD(localStorage.zip);
}

//search function - zip
fall2012P3.getZD = function (n) {
    var output = document.getElementById("outcome");
    output.innerHTML = "";
    var transaction = fall2012P3.db.transaction('farmers', 'readonly');
    var objectStore = transaction.objectStore("farmers");
    var index = objectStore.index("Zip");
    var singleKeyRange = IDBKeyRange.only(String(n));
    index.openCursor(singleKeyRange).onsuccess = function (event) {
        var cursor = event.target.result;
        if (cursor) {
            output.innerHTML += '<div class = "inside">' +
			'<input type="radio" name="requestRadio" value="' +
			cursor.value.ID + '" onclick="fall2012P3.setID(this.value)">' +
			'<span style="font-weight: bold;">' + cursor.value.MarketName + '</span>' +
			", " + cursor.value.Street + ", " +
			cursor.value.City + ", " + cursor.value.State + ", " + cursor.value.Zip + " " +
			'</div>' + '<hr class="linie"/>';

            fall2012P3.curentID = cursor.value.ID;

            cursor.continue();

        }
    };
}

//set id
fall2012P3.setID = function (i) {
    fall2012P3.curentID = i;
    document.getElementById('searchDetails').disabled = false;
}

//initial setup function
fall2012P3.setup = function () {
    fall2012P3.setupDB();
    fall2012P3.setFirst();
    fall2012P3.setZip();
}

//set favorite zip in local storage
fall2012P3.setZip = function () {
    localStorage.zip = document.getElementById("zipFavorit").value;
}

//new zip 
fall2012P3.newZip = function () {
    document.getElementById("resetDiv").style.display = '';
    document.getElementById("locationDiv").style.display = 'none';
    document.getElementById("mapDiv").style.display = 'none';
    document.getElementById("searchDiv").style.display = 'none';
}

//set zip again
fall2012P3.setZipAgain = function () {
    if (document.getElementById("zipFavorit2").value === "" || Number(document.getElementById("zipFavorit2").value) === 0) {
        alert('Please enter a valid zip code!');
        document.getElementById("resetDiv").style.display = '';
        document.getElementById("locationDiv").style.display = 'none';
        document.getElementById("mapDiv").style.display = 'none';
        document.getElementById("searchDiv").style.display = 'none';
    } else {
        localStorage.zip = document.getElementById("zipFavorit2").value;
        fall2012P3.onSuccessZip();
        document.getElementById("locationDiv").style.display = 'none';
        document.getElementById("mapDiv").style.display = 'none';
        document.getElementById("resetDiv").style.display = 'none';
        document.getElementById("searchDiv").style.display = '';
    }


}

//go to search page - refresh page
fall2012P3.goBack = function () {
    fall2012P3.init();
}

//display terms
fall2012P3.arataDetails = function () {
    //display map div
    document.getElementById("locationDiv").style.display = 'none';
    document.getElementById("searchDiv").style.display = 'none';
    document.getElementById("resetDiv").style.display = 'none';
    document.getElementById("mapDiv").style.display = '';

    var d = document.getElementById('detalii');

    var transaction = fall2012P3.db.transaction('farmers', 'readonly');
    var store = transaction.objectStore("farmers");

    var cerere = store.get(Number(fall2012P3.curentID));
    cerere.onsuccess = function () {

        if (cerere.result.Website) {
            if (cerere.result.Schedule) {
                d.innerHTML = "<span class='bold'>" +
                cerere.result.MarketName + "</span>" + "<br/>" +
                cerere.result.Street + "<br/>" +
                cerere.result.City + ", " +
                cerere.result.Zip + "<br/>" +
                "<span class='bold'>" + "Schedule: " + "</span>" + cerere.result.Schedule + "<br/>" +
                '<a class="sub" onclick="fall2012P3.openNewWindow(this)" data-web="' + cerere.result.Website + '">' + "Website" + "</a>";
            } else {
                d.innerHTML = "<span class='bold'>" +
                cerere.result.MarketName + "</span>" + "<br/>" +
                cerere.result.Street + "<br/>" +
                cerere.result.City + ", " +
                cerere.result.Zip + "<br/>" +
                '<a class="sub" onclick="fall2012P3.openNewWindow(this)" data-web="' + cerere.result.Website + '">' + "Website" + "</a>";
            }


        } else {
            if (cerere.result.Schedule) {
                d.innerHTML = "<span class='bold'>" +
                cerere.result.MarketName + "</span>" + "<br/>" +
                cerere.result.Street + "<br/>" +
                cerere.result.City + ", " +
                cerere.result.Zip + "<br/>" +
                "<span class='bold'>" + "Schedule: " + "</span>" + cerere.result.Schedule + "<br/>";
            } else {
                d.innerHTML = "<span class='bold'>" +
                cerere.result.MarketName + "</span>" + "<br/>" +
                cerere.result.Street + "<br/>" +
                cerere.result.City + ", " +
                cerere.result.Zip + "<br/>";
            }
        }

    }
    //map location
    fall2012P3.mapMe();
}

fall2012P3.openNewWindow = function (t) {
    if (t.getAttribute('data-web')) {
        var w = t.getAttribute('data-web');
        window.open(w, "_blank");
    }

}

//display farmer on map
fall2012P3.mapMe = function () {

    var transaction = fall2012P3.db.transaction('farmers', 'readonly');
    var store = transaction.objectStore("farmers");

    var cerere = store.get(Number(fall2012P3.curentID));
    cerere.onsuccess = function () {

        //google map
        var latlng = new google.maps.LatLng(cerere.result.y, cerere.result.x);
        var myOptions = {
            zoom: 13,
            center: latlng,
            panControl: true,
            zoomControl: true,
            scaleControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var localMap = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        var marker = new google.maps.Marker({
            position: latlng,
            map: localMap,
            title: cerere.result.MarketName
        });
    }

}
