/**
 * Generates javascript for client functionality from 51Degrees data.
 */
function fiftyone_degrees_get_script()
{
    global $_fiftyone_degrees_needed_properties;
    $headers = fiftyone_degrees_get_headers();
    $_fiftyone_degrees_needed_properties = array();
    $profile_scripts = array();
    $other_scripts = array();
    $output = "\n";
    for ($i = 0; $i < $headers['property_count']; $i++) {
        $property = fiftyone_degrees_read_property($i, $headers);
        if ($property['value_type_id'] == 4) {
            $_fiftyone_degrees_needed_properties[] = $property['name'];
            if (strpos($property['name'], 'Profile') !== FALSE) {
                $profile_scripts[] = $property['name'];
            } else {
                $other_scripts[] = $property['name'];
            }
        }
    }
    $_51d = fiftyone_degrees_get_device_data($_SERVER['HTTP_USER_AGENT']);
    foreach ($other_scripts as $property) {
        if (isset($_51d[$property])) {
            $output .= $_51d[$property];
            $output .= "\n";
        }
    }
    $output .= "function FODPO() { var profileIds = new Array();\n";
    $c = count($profile_scripts);
    if ($c > 0 && (isset($_SESSION['51D_ProfileIds']) === FALSE || strlen($_SESSION['51D_ProfileIds']) == 0)) {
        foreach ($profile_scripts as $property) {
            if (isset($_51d[$property])) {
                $props = $_51d[$property];
                foreach ($props as $prop) {
                    $output .= $prop;
                    $output .= "\n";
                }
            }
        }
        $output .= "document.cookie = \"51D_ProfileIds=\" + profileIds.join(\"|\");";
    }
    $output .= "}\n";
    return str_replace('document.addEventListener("load", this.loadComplete.bind(this), true);', 'window.addEventListener("load", this.loadComplete.bind(this), true);', $output);
}
function fiftyone_degrees_echo_profile_images($hardware_vendor, $headers)
{
    // Get needed hardware vendor
    $hardware_vendor_id = -1;
    for ($i = 0; $i < $headers['property_count']; $i++) {
        $property = fiftyone_degrees_read_property($i, $headers);
        if ($property['name'] == 'HardwareVendor') {
            $hardware_vendor_id = $property['index'];
            break;
        }
    }
    $hardware_value_id = -1;
    for ($i = 0; $i < $headers['values_count']; $i++) {
        $property_value = fiftyone_degrees_read_property_value($i, $headers);
        if ($property_value['property_index'] == $hardware_vendor_id && $property_value['value'] == $hardware_vendor) {
            $hardware_value_id = $property_value['index'];
            break;
        }
    }
    $offset = 0;
    if (array_key_exists('next', $_GET) && is_numeric($_GET['next'])) {
        $offset = (int) $_GET['next'];
    }
    $profile_offsets = array();
    $profiles = fiftyone_degrees_gallery_get_profiles($offset, 25, $hardware_value_id, $headers);
    foreach ($profiles as $profile) {
        $props = fiftyone_degrees_get_property_data(array($profile), $headers);
        $images = array();
        foreach ($props['HardwareImages'] as $image) {
            $parts = explode("\t", $image);
            $caption = $parts[0];
            $images[] = $parts[1];
        }
        $first_image = $images[0];
        $profile_id = $props['DeviceId'];
        $model = $props['HardwareModel'];
        $name = $props['HardwareName'][0];
        $mouse_over = implode("','", $images);
        echo '<div class="item">';
        echo '<div class="model">';
        echo "<a href=\"Device.php?ProfileId={$profile_id}\">{$model}</a>";
        echo '</div>';
        echo '<div class="image">';
        echo "<a href=\"Device.php?ProfileId={$profile_id}\">";
        echo "<img src=\"{$first_image}\" style=\"height:128px;width:128px;\" ";
        if (count($images) > 1) {
            echo "onmouseover=\"ImageHovered(this, new Array('{$mouse_over}'))\" onmouseout=\"ImageUnHovered(this, '{$first_image}')\"";
        }
        echo "/>";
        echo '</a>';
        echo '</div>';
        echo '<div class="name">';
        echo "<a href=\"Device.php?ProfileId={$profile_id}\">{$name}</a>";
        echo '</div>';
        echo "</div>";
    }
    echo "<div style=\"clear: both; \" ><a href=\"Devices.php?vendor={$hardware_vendor}&next={$offset}\">Next</a></div>";
}
function fiftyone_degrees_get_profile_property_values($profile, $needed_properties, $headers)
{
    global $_fiftyone_degrees_return_strings;
    $values = array();
    foreach ($profile['profile_values'] as $value) {
        if (fiftyone_degrees_is_needed_value($needed_properties, $value)) {
            $property_value = fiftyone_degrees_read_property_value($value, $headers);
            $property = fiftyone_degrees_read_property($property_value['property_index'], $headers);
            if ($_fiftyone_degrees_return_strings === FALSE) {
                $value = $property_value['value'];
            } else {
                $value = fiftyone_degrees_get_typed_value($property, $property_value);
            }
            if ($property['list']) {
                if (!isset($values[$property['name']])) {
                    $values[$property['name']] = array();
                }
                $values[$property['name']][] = $value;
            } else {
                $values[$property['name']] = $value;
            }
        }
    }
    return $values;
}
/**
 * Returns an array with properties in the data set and their values.
 *
 * @return array
 *   Properties and their values.
 */
function fiftyone_degrees_get_meta_data()
{
    fiftyone_degrees_set_file_handle();
    $headers = fiftyone_degrees_get_headers();
    $name = fiftyone_degrees_get_dataset_name($headers);
    $cache_file_name = dirname(__FILE__) . "/51Degrees_meta_data_cache_{$headers['info']['published_year']}_{$headers['info']['published_month']}_{$headers['info']['published_day']}_{$name}.cache";
    $cache_file_name = str_replace("\\", "/", $cache_file_name);
    if (file_exists($cache_file_name)) {
        $cache = file_get_contents($cache_file_name);
        $meta_data = unserialize($cache);
        if ($meta_data !== FALSE) {
            return $meta_data;
        }
    }
    $meta_data = array();
    $meta_data['Date'] = "{$headers['info']['published_month']}/{$headers['info']['published_day']}/{$headers['info']['published_year']}";
    $meta_data['DatasetName'] = fiftyone_degrees_get_dataset_name($headers);
    $property_names = array();
    $value_indexes = array();
    for ($i = 0; $i < $headers['property_count']; $i++) {
        $property = fiftyone_degrees_read_property($i, $headers);
        $meta_data[$property['name']] = array();
        $meta_data[$property['name']]['Description'] = fiftyone_degrees_read_ascii($property['description_offset'], $headers);
        $meta_data[$property['name']]['List'] = $property['list'];
        if ($property['url_offset'] != -1) {
            $meta_data[$property['name']]['Url'] = fiftyone_degrees_read_ascii($property['url_offset'], $headers);
        }
        $property_names[$i] = $property['name'];
        $meta_data[$property['name']]['Values'] = array();
        $value_indexes[] = array('first_value_index' => $property['first_value_index'], 'last_value_index' => $property['last_value_index']);
        switch ($property['value_type_id']) {
            case 0:
                // string
            // string
            default:
                $value_type = 'string';
                break;
            case 1:
                // int
                $value_type = 'integer';
                break;
            case 2:
                // double
                $value_type = 'double';
                break;
            case 3:
                // bool
                $value_type = 'boolean';
                break;
            case 4:
                // javaScript
                $value_type = 'javascript';
                break;
        }
        $meta_data[$property['name']]['ValueType'] = $value_type;
    }
    foreach ($value_indexes as $value_index) {
        for ($i = $value_index['first_value_index']; $i <= $value_index['last_value_index']; $i++) {
            $property_value = fiftyone_degrees_read_property_value($i, $headers);
            $name = $property_names[$property_value['property_index']];
            $meta_data[$name]['Values'][$property_value['value']] = array();
            if ($property_value['description_offset'] > 0) {
                $meta_data[$name]['Values'][$property_value['value']]['Description'] = fiftyone_degrees_read_ascii($property_value['description_offset'], $headers);
            }
            if ($property_value['url_offset'] > 0) {
                $meta_data[$name]['Values'][$property_value['value']]['Url'] = fiftyone_degrees_read_ascii($property_value['url_offset'], $headers);
            }
        }
    }
    $handle = fopen($cache_file_name, "w");
    if ($handle !== FALSE) {
        $dir = new DirectoryIterator(dirname(__FILE__));
        foreach ($dir as $fileinfo) {
            if ($fileinfo->isFile()) {
                $file_extension = pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION);
                if ($file_extension === "cache" && strpos($fileinfo->getFilename(), '51Degrees_meta_data_cache_') === 0) {
                    $path = $fileinfo->getRealPath();
                    @unlink($path);
                }
            }
        }
        $cache = serialize($meta_data);
        fwrite($handle, $cache);
    }
    return $meta_data;
}